如何获取`std :: function`的参数个数?

Yun*_*ang 15 c++ function c++11

这有可能获得参数的数量std::function吗?有点像NumOfArgument<...>::value.

例如,NumOfArgument<function<int(int, int)> >::value应该是2.

Naw*_*waz 44

我认为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);
};
Run Code Online (Sandbox Code Playgroud)

测试代码:

typedef std::function<int(int, int)> fun;
std::cout << count_arg<fun>::value << std::endl; //should print 2
Run Code Online (Sandbox Code Playgroud)

见:在线演示


同样,您可以在其中添加更多功能,如:

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;
    };
};
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用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;
Run Code Online (Sandbox Code Playgroud)

工作演示

它打印出类型的错位名称!

  • +1:哇,一旦你有可变模板工作O__O就变得非常简单; (5认同)
  • @iammilind:`sizeof ...(T)`是一个特殊的语法来获取参数包`T`的大小.它与`sizeof(T)`(§5.3.3/ 5,§14.5.3/ 7)无关. (4认同)