[英]Compiler can't deduce template parameter in basic function
I have a template function, whose type depends on type parameters. 我有一个模板函数,其类型取决于类型参数。 The compiler can't deduce template parameter even if it's obvious.
即使很明显,编译器也无法推断出模板参数。 This is a basic code and even here it doesn't know it is an
int
( int
is just example). 这是一个基本代码,即使在这里它也不知道它是一个
int
( int
只是示例)。 What should be changed to make it work? 应该进行哪些更改才能使其正常工作?
#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;
}
Compiler can only deduce template type arguments only from function arguments types, not from result type. 编译器只能从函数参数类型推断出模板类型参数,而不能从结果类型推断出模板类型参数。 To make it work without changing function template you need to explicitly specify type argument:
要使其工作而不更改功能模板,您需要显式指定type参数:
cout << pr<int>('A');
But it is probably better to change the definition, since T1
parameter doesn't seem to be useful: 但是更改定义可能更好,因为
T1
参数似乎没有用:
template<class T>
int pr (T w){
return int(w);
}
In C++11 you can use trailing return type, which might be useful in more complex situations: 在C ++ 11中,可以使用尾随返回类型,这在更复杂的情况下可能很有用:
template<class T>
auto pr (T w) -> decltype(int(w)) {
return int(w);
}
And finally C++14 has return type deduction, so ther it is simply: 最后,C ++ 14具有返回类型推导,因此它很简单:
template<class T>
auto pr (T w) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.