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.
Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.
Neither the C nor C++ standard places an absolute requirement on the number of arguments/parameters you must be able to pass when calling a function, but the C standard suggests that an implementation should support at least 127 parameters/arguments (§5.2.
While a function can only have one argument of variable length of each type, we can combine both types of functions in one argument.
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;
Working demo
It prints the mangled-name of the types!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With