C++11 不能';t从模板类推断方法的第二个模板参数
以以下为例:C++11 不能';t从模板类推断方法的第二个模板参数,c++11,templates,type-deduction,C++11,Templates,Type Deduction,以以下为例: template < class T > struct Dummy { typedef const T & type; }; struct Type { int i = 0; bool operator == (const Type & o) { return i == o.i; } }; template < class T > struct Test { template < class U &
template < class T > struct Dummy
{
typedef const T & type;
};
struct Type
{
int i = 0;
bool operator == (const Type & o) { return i == o.i; }
};
template < class T > struct Test
{
template < class U >
bool F(typename Dummy< T >::type a, typename Dummy< U >::type b) const
{
return a == b; // dummy operation
}
};
int main()
{
Type a, b;
// error: no matching function for call to 'Test<Type>::F(Type&, Type&)'
// note: template argument deduction/substitution failed:
// note: couldn't deduce template parameter 'U'
bool x = Test<Type>{}.F(a, b);
}
templatestruct-Dummy
{
typedef const T&type;
};
结构类型
{
int i=0;
布尔运算符==(常量类型&o){return i==o.i;}
};
模板结构测试
{
模板
bool F(typename伪::type a,typename伪::type b)常量
{
返回a==b;//伪操作
}
};
int main()
{
a、b型;
//错误:对“Test::F(Type&,Type&)”的调用没有匹配的函数
//注意:模板参数扣除/替换失败:
//注意:无法推断模板参数“U”
boolx=测试{}.F(a,b);
}
我从编译器那里得到一个错误,该方法的第二个参数无法推导。我做错了什么?这样的类型推断是不可能的。左侧的类
:
是模板参数的非推断上下文
原因很简单:编译器必须尝试所有可能的U
s,并查看其中任何一个Dummy
是否具有与作为参数提供的内容匹配的嵌套类型。记住模板专业化是存在的!您完全有可能专门从事Dummy
,使其Dummy::type
为type