Function return type deduction in C++03

心已入冬 提交于 2020-01-01 07:01:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!