boost—— 函数与回调result_of小工具类

/*result_of是一个利用复杂技巧来推导函数返回值类型的小工具类
* 部分摘要如下:
* template struct result_of;
* struct result_of_private_type {};
* struct result_of_weird_type {
* friend result_of_private_type operator,
* (result_of_private_type, result_of_weird_type);};
* typedef char result_of_yes_type; // sizeof(result_of_yes_type) == 1
* typedef char (&result_of_no_type)[2]; // sizeof(result_of_no_type) == 2
* template
* result_of_no_type result_of_is_private_type(T const &);
* result_of_yes_type result_of_is_private_type(result_of_private_type);
*……..

主要特点:
1.相比于BOOST_AUTO,其适用性更强大;
2.依赖编译器相对较强
3.不仅用于函数指针,还可用于函数对象的泛型编程,利用到了C++高级特性,如模板偏特化和SFINAE

  获取返回值的类型:result_of<....>::type.
  例如:result_of<Func(T1,T2)>::type.其中Func可是函数指针、函数引用或函数对象
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <boost/utility/result_of.hpp>
#include <math.h>
#include <typeinfo>
#include <boost/typeof/typeof.hpp>

using namespace boost;
using namespace std;



template<typename T,typename T1>
typename result_of<T(T1)>::type call_func(T t,T1 t1)
{
     return t(t1);
}
int main( int argc,char **argv)
{
    typedef double (*Func)(double d);
    Func func = sqrt;
    result_of<Func(double)>::type x = func(5.0);
    cout << typeid(x).name() << endl;
    cout << "x = " << x << endl;

    typedef double (*Func1)(double d);
    Func1 func1 = sqrt;
    BOOST_AUTO(x1,call_func(func,5.0));
    cout << "x1 = " << x1 << endl;
    cout << typeid(x1).name() << endl;

     return (0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值