【发布时间】:2012-02-21 03:00:24
【问题描述】:
是否有可能获得 std::function 的参数数量?类似于NumOfArgument<...>::value。
例如,NumOfArgument<function<int(int, int)> >::value 应该是 2。
【问题讨论】:
-
您有什么特别的理由要首先这样做吗?
是否有可能获得 std::function 的参数数量?类似于NumOfArgument<...>::value。
例如,NumOfArgument<function<int(int, int)> >::value 应该是 2。
【问题讨论】:
我认为std::function 本身不提供该功能。但是你可以自己实现它:
template<typename T>
struct count_arg;
template<typename R, typename ...Args>
struct count_arg<std::function<R(Args...)>>
{
static const size_t value = sizeof...(Args);
};
测试代码:
typedef std::function<int(int, int)> fun;
std::cout << count_arg<fun>::value << std::endl; //should print 2
看到这个:Online demo
同样,您可以在其中添加更多功能,例如:
template<typename T>
struct function_traits; //renamed it!
template<typename R, typename ...Args>
struct function_traits<std::function<R(Args...)>>
{
static const size_t nargs = sizeof...(Args);
typedef R result_type;
template <size_t i>
struct arg
{
typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
};
};
现在您可以使用 const 索引获取每个参数类型,如下所示:
std::cout << typeid(function_traits<fun>::arg<0>::type).name() << std::endl;
std::cout << typeid(function_traits<fun>::arg<1>::type).name() << std::endl;
std::cout << typeid(function_traits<fun>::arg<2>::type).name() << std::endl;
它打印类型的错位名称!
【讨论】:
sizeof...(Args) 是正确的语法! sizeof() 对 Args 有特殊含义吗?因为一般sizeof()只处理数据类型的大小而不是元素的数量。
sizeof...(T) 是获取参数包大小的特殊语法T。它与sizeof(T) 无关(§5.3.3/5、§14.5.3/7)。
nargs 应该真的是 size_t 以与 struct arg 保持一致...因为它无论如何都不能是负数。