我创建了两个简单的函数,它们获取模板参数和一个定义类型的空结构:
//S<T>::type results in T&
template <class T>
struct S
{
typedef typename T& type;
};
//Example 1: get one parameter by reference and return it by value
template <class A>
A
temp(typename S<A>::type a1)
{
return a1;
}
//Example 2: get two parameters by reference, perform the sum and return it
template <class A, class B>
B
temp2(typename S<A>::type a1, B a2)//typename struct S<B>::type a2)
{
return a1 + a2;
}
参数类型应用于结构 S 以获取引用。我用一些整数值调用它们,但编译器无法推断出参数:
int main()
{
char c=6;
int d=7;
int res = temp(c);
int res2 = temp2(d,7);
}
Error 1 error C2783: 'A temp(S::type)' : could not deduce template argument for 'A'
Error 2 error C2783: 'B temp2(S::type,B)' : could not deduce template argument for 'A'
为什么会这样?很难看出模板参数是 char 和 int 值吗?
最佳答案
就像第一个注释一样,当您提到 从属 名称时,会使用 typename 名称。所以这里不需要它。
template <class T>
struct S
{
typedef T& type;
};
关于模板实例化,问题是typename S<A>::type
表征 A 的 非推导 上下文。当模板参数仅用于非推导上下文(函数中的 A 的情况)时,模板参数推导不会考虑它。详细信息在 C++ 标准 (2003) 的第 14.8.2.4 节中。
要使您的调用正常工作,您需要明确指定类型:
temp<char>(c);
关于c++ - 为什么模板参数推导在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1268504/