简体   繁体   中英

Function return type deduction in C++03

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.

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.

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