Reputation: 11
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). 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;
}
Upvotes: 1
Views: 75
Reputation: 15278
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:
cout << pr<int>('A');
But it is probably better to change the definition, since T1
parameter doesn't seem to be useful:
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:
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:
template<class T>
auto pr (T w) {
Upvotes: 2