下のコードで、19、20行目をそれぞれget<int>, get<char>と書き直せばコンパイルが通ることは確認しました。
しかし、例えばmax関数はmax<int>と書かなくてもmax(1,2)のように呼びだせば自動でint型と判断され、のint型の2が返ってきますが、このような推論を関数の引数ではなく戻り値で行うにはどうすればよいのでしょうか。
#include <cstdio>
void get(int &i){
scanf("%d",&i);
}
void get(char &c){
scanf("%c",&c);
}
template<typename T>
T get(){
T t;
get(t);
return t;
}
int main(){
int i=get(); // ここではT get(),void get(char &c)が呼ばれ、
char c=get(); // ここではT get(),void get(int &)が呼ばれてほしい
}
test.cpp: In function ‘int main()’:
test.cpp:19:15: error: no matching function for call to ‘get()’
int i=get();
^
test.cpp:19:15: note: candidate is:
test.cpp:12:3: note: template<class T> T get()
T get(){
^
test.cpp:12:3: note: template argument deduction/substitution failed:
test.cpp:19:15: note: couldn't deduce template parameter ‘T’
int i=get();
^
test.cpp:20:16: error: no matching function for call to ‘get()’
char c=get();
^
test.cpp:20:16: note: candidate is:
test.cpp:12:3: note: template<class T> T get()
T get(){
^
test.cpp:12:3: note: template argument deduction/substitution failed:
test.cpp:20:16: note: couldn't deduce template parameter ‘T’
char c=get();