函数返回类型在C ++ 03中扣除 [英] Function return type deduction in C++03

查看:155
本文介绍了函数返回类型在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');
}

如果删除参数R并且手动插入int,编译器会很乐意编译返回类型。如图所示,编译器无法知道要做什么。

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.

如何在C ++ 03中推导函数返回类型?

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.

推荐答案

如果限制函数指针,partial可以使用特殊化,例如

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.

这篇关于函数返回类型在C ++ 03中扣除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆