boost function_traits

template <class F>
struct function_traits
{
   static const std::size_t    arity = see-below;
   typedef see-below           result_type;
   typedef see-below           argN_type;
};
function_traits类模板只在满足以下条件的时候才编译:

· 编译器支持类模板偏特化

· 模板参数F是函数类型,请注意函数类型和函数指针类型不是一回事。

提示

function_traits只针对形如R(),R(A1),R(A1, ...etc.)的C++函数类型,而不是函数指针类型或者类成员函数类型。remove_pointer可以将函数指针类型转换为相应的函数类型。

Table 1.19. Function Traits 成员函数

Member

Description

function_traits<F>::arity

表示函数F参数数目的整形常量表达式.

function_traits<F>::result_type

函数F的返回值类型

function_traits<F>::argN_type

函数F的第N个参数类型,其中1<=N<=arity

 

Table 1.20. 例子

Expression

Result

function_traits<void (void)>::arity

值为0的整形常量表达式

function_traits<long (int)>::arity

值为1的整形常量表达式

function_traits<long (int, long, double,void*)>::arity

值为4的整形常量表达式

function_traits<void (void)>::result_type

void类型.

function_traits<long (int)>::result_type

long类型

function_traits<long (int)>::arg1_type

int类型

function_traits<long (int, long, double,void*)>::arg4_type

void*类型

function_traits<long (int, long, double,void*)>::arg5_type

编译错误,只有第4个参数,所以第5个参数不存在

function_traits<long (*)(void)>::arity

编译错误,参数类型是函数指针类型,不是函数类型

实现细节如下:
template<typename Function>
struct function_traits_helper;
 
template<typename R>
struct function_traits_helper<R (*)(void)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 0);
  typedef R result_type;
};
 
template<typename R, typename T1>
struct function_traits_helper<R (*)(T1)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 1);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T1 argument_type;
};
 
template<typename R, typename T1, typename T2>
struct function_traits_helper<R (*)(T1, T2)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 2);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T1 first_argument_type;
  typedef T2 second_argument_type;
};
 
template<typename R, typename T1, typename T2, typename T3>
struct function_traits_helper<R (*)(T1, T2, T3)>
{
  BOOST_STATIC_CONSTANT(unsigned, arity = 3);
  typedef R result_type;
  typedef T1 arg1_type;
  typedef T2 arg2_type;
  typedef T3 arg3_type;
};
 
template<typename Function>
struct function_traits : public function_traits_helper<typename boost::add_pointer<Function>::type>
{
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值