Reputation: 4386
Is that possible to get the number of arguments of std::function
? Something like NumOfArgument<...>::value
.
For example, NumOfArgument<function<int(int, int)> >::value
should be 2.
Upvotes: 16
Views: 6552
Reputation: 361472
I think std::function
itself doesn't provide that feature. But you can implement it yourself as:
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);
};
Test code:
typedef std::function<int(int, int)> fun;
std::cout << count_arg<fun>::value << std::endl; //should print 2
See this : Online demo
Likewise, you may put more features into this, as :
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;
};
};
Now you can get each argument type, using const index, as:
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;
It prints the mangled-name of the types!
Upvotes: 48