Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of arguments of `std::function`?

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.

like image 341
Yun Huang Avatar asked Jan 28 '12 11:01

Yun Huang


People also ask

How many arguments can a function received?

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.

How many arguments can be used in a function in C?

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.

What is the minimum number of arguments that functions can have?

While a function can only have one argument of variable length of each type, we can combine both types of functions in one argument.


1 Answers

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!

like image 136
Nawaz Avatar answered Oct 02 '22 18:10

Nawaz