为什么模板参数扣除不工作在这里? [英] Why is the template argument deduction not working here?
问题描述
我创建了两个简单的函数,它们获得模板参数和一个定义类型的空结构:
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;
}
参数类型应用于struct S以获取引用。我用一些整数值调用它们,但编译器无法推导出参数:
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);
}
错误1错误C2783:'A
temp(S :: type)':无法推导出'A'的
模板参数
Error 1 error C2783: 'A temp(S::type)' : could not deduce template argument for 'A'
错误2错误C2783:'B
temp2(S :: type,B)':can not
推导'A'的模板参数
Error 2 error C2783: 'B temp2(S::type,B)' : could not deduce template argument for 'A'
为什么会发生这种情况?难道看到模板参数是 char 和 int 值吗?
推荐答案
正如第一个注意,当你提到一个从属名称时,会使用typename名称。所以你不需要它。
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;
};
< :type 表示A的
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);
这篇关于为什么模板参数扣除不工作在这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!