为什么模板参数扣除不工作在这里? [英] Why is the template argument deduction not working here?

查看:118
本文介绍了为什么模板参数扣除不工作在这里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个简单的函数,它们获得模板参数和一个定义类型的空结构:

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的非隐藏上下文。当模板参数仅用于非隐藏上下文(在函数中为A的情况)时,模板不被考虑参数扣除。详细信息在C ++标准(2003)的第14.8.2.4节。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆