如何获得`std :: function`的参数个数? [英] How to get the number of arguments of `std::function`?
问题描述
可以得到 std :: function
的参数个数吗?类似于 NumOfArgument< ...>值
。
例如, NumOfArgument< function< int(int,int)> > :: value
应该是2.
我认为 std :: function
本身不提供该功能。但你可以自己实现它:
template< typename T>
struct count_arg;
模板< typename R,typename ... Args>
struct count_arg< std :: function< R(Args ...)>>
{
static const size_t value = sizeof ...(Args);
};
测试代码:
typedef std :: function< int(int,int)>乐趣;
std :: cout<< count_arg< fun> :: value<<的std :: ENDL; //应该打印2
请参阅:在线演示
同样,您可以将更多功能放入其中, as:
模板< typename T>
struct function_traits; //重命名它!
模板< typename R,typename ... Args>
struct function_traits< std :: function< R(Args ...)>>
{
static const size_t nargs = sizeof ...(Args);
typedef R result_type;
模板< 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;
它打印类型的损坏名称!
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.
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!
这篇关于如何获得`std :: function`的参数个数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!