c++ - 为什么模板参数推导在这里不起作用?

标签 c++ templates

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

//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'


为什么会这样?很难看出模板参数是 charint 值吗?

最佳答案

就像第一个注释一样,当您提到 从属 名称时,会使用 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/

相关文章:

c++ - MSVS 2015 构建 dll - MSVCRTD.lib (exe_main.obj) 中 invoke_main 中未解析的外部符号 _main

c++ - 模板类的静态常量成员

c++ - 在 async_write 挂起时写入 streambuf 是否安全?

c++ - 右淡化文本优化

c# - 从托管应用程序使用 native 注册免费 C++ COM 服务器

c++ - 将 std::vector 作为模板模板参数传递时出错 - 在 GCC 中有效,在 MSVC 中失败

c++ - 错误 : there are no arguments to 'at' that depend on a template parameter, 因此 at 的声明必须可用

c++ - 模板函数中的静态变量似乎不是模板实例所独有的

ruby - Rails 5 渲染部分并传递数据

c++ - Eclipse Juno Indexer Broken - 找不到任何 STL header