简体   繁体   中英

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). 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:

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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM