问题
The tags ask the question, but nonetheless, consider the following:
template<typename F, typename A, typename R>
R call(F function, A arg) {
return function(arg);
}
int foo(char) {
return 5;
}
int main() {
call(foo, 'a');
}
The compiler happily compiles this if parameter R is removed and int is inserted manually as the return type. As shown, the compiler has no way of knowing what to make of R.
How can I deduce function return types in C++03?
I'm looking for methods that do not require manually specifying the return type and do not require intrusive changes to the other parameters. If this is not possible then I'm just looking for an authoritative statement verifying that.
回答1:
If limited to function pointers, partial specializations can be used, something like
template<class T> struct func_ptr_result {};
template<class R>
struct func_ptr_result<R (*)()> {
typedef R type;
};
template<class R, class Arg1>
struct func_ptr_result<R (*)(Arg1)> {
typedef R type;
};
// etc for > 1 arguments
template<typename F, typename A>
typename func_ptr_result<F>::type call(F function, A arg) {
return function(arg);
}
In the more general case (arbitrary functors), it isn't possible without compiler support or cooperation from the type.
来源:https://stackoverflow.com/questions/26080471/function-return-type-deduction-in-c03