我创建了两个简单的函数,它们获取模板参数和一个定义类型的空结构:
//S::type 结果为 T&模板结构体{typedef typename T&类型;};//示例1:通过引用获取一个参数并通过值返回模板<A类>一个temp(typename S<A>::type a1){返回 a1;}//例2:通过引用获取两个参数,求和返回模板<A类,B类>乙temp2(typename S<A>::type a1, B a2)//typename struct S<B>::type a2){返回 a1 + a2;}
参数类型应用于结构体 S 以获取引用.我用一些整数值调用它们,但编译器无法推导出参数:
int main(){字符 c=6;整数 d=7;int res = temp(c);int res2 = temp2(d,7);}
<块引用>
错误 1 错误 C2783:'Atemp(S::type)' : 无法推断'A' 的模板参数
错误 2 错误 C2783:'Btemp2(S::type,B)' : 不能推导出 'A' 的模板参数
为什么会这样?很难看出模板参数是 char 和 int 值吗?
正如第一个注意事项,当您提到一个从属名称时,会使用 typename 名称.所以你在这里不需要它.
<代码>模板结构体{typedef T& type;};
关于模板实例化,问题在于 typename S<A>::type
描述了 A 的 nondeduced 上下文.当模板参数仅用于非推导的上下文(函数中 A 的情况)不考虑模板参数推导.详细信息位于 C++ 标准 (2003) 的第 14.8.2.4 节.
要使您的通话正常工作,您需要明确指定类型:
<代码>温度<字符>(c);
I created two simple functions which get template parameters and an empty struct defining a type:
//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;
}
The argument type is applied to the struct S to get the reference. I call them with some integer values but the compiler is unable to deduce the arguments:
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'
Why is this happening? Is it that hard to see that the template arguments are char and int values?
Just as first note, typename name is used when you mention a dependent name. So you don't need it here.
template <class T>
struct S
{
typedef T& type;
};
Regarding the template instantiation, the problem is that typename S<A>::type
characterizes a nondeduced context for A. When a template parameter is used only in a nondeduced context (the case for A in your functions) it's not taken into consideration for template argument deduction. The details are at section 14.8.2.4 of the C++ Standard (2003).
To make your call work, you need to explicitly specify the type:
temp<char>(c);
这篇关于为什么模板参数推导在这里不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!