编译器不能在基本功能中推导出模板参数

时间:2014-11-26 20:33:43

标签: c++ templates

我有一个模板函数,其类型取决于类型参数。即使显而易见,编译器也无法推断出模板参数。这是一个基本代码,即使在这里它也不知道它是intint只是示例)。应该改变什么才能使它发挥作用?

#include <iostream>
using namespace std;

template<class T1, class T2>
T1 pr (T2 w) {
    return int(w);
}

int main() {
cout<<pr('A');  // your code goes here
    return 0;
}

1 个答案:

答案 0 :(得分:2)

编译器只能从函数参数类型推导出模板类型参数,而不能从结果类型推断出。要使其在不更改函数模板的情况下工作,您需要显式指定类型参数:

cout << pr<int>('A');

但更改定义可能更好,因为T1参数似乎没有用处:

template<class T>
int pr (T w){
    return int(w);
}

在C ++ 11中,您可以使用尾随返回类型,这在更复杂的情况下可能很有用:

template<class T>
auto pr (T w) -> decltype(int(w)) {
    return int(w);
}

最后C ++ 14具有返回类型推导,所以它只是:

template<class T>
auto pr (T w) {
相关问题