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 |
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>
{
};