Type inference of return type in C ++ 03

Tags ask a 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 the R parameter is removed and the int is manually inserted as the return type. As shown, the compiler does not know what to do with R.

How can I deduce return function types in C ++ 03?

I am looking for methods that do not require manual indication of the return type and do not require intrusive changes for other parameters. If this is not possible, I am simply looking for an authoritative statement confirming that.

+3
source share
1 answer

If restricted to function pointers, partial specializations can be used, for example,

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);
}

( ) .

+5

All Articles