这是后续如何获取可变参数模板类中函数指针的参数类型? https://stackoverflow.com/questions/9065081/how-do-i-get-the-argument-types-of-a-function-pointer-in-a-variadic-template-cla
我有这个结构来访问可变参数模板的参数:
template<typename T>
struct function_traits;
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;
};
};
我访问 Args 参数的类型
typedef function<void(Args...)> fun;
std::cout << std::is_same<int, typename function_traits<fun>::template arg<0>::type>::value << std::endl;
但是,我想迭代参数以便能够处理任意数量的参数。以下不起作用,但为了说明我想要的:
for (int i = 0; i < typename function_traits<fun>::nargs ; i++){
std::cout << std::is_same<int, typename function_traits<fun>::template arg<i>::type>::value << std::endl;
}
您需要按照以下方式进行编译时迭代
template <typename fun, size_t i> struct print_helper {
static void print() {
print_helper<fun, i-1>::print();
std::cout << std::is_same<int, typename function_traits<fun>::template arg<i-1>::type>::value << std::endl;
}
};
template <typename fun> struct print_helper<fun,0> {
static void print() {}
};
template <typename fun> void print() {
print_helper<fun, function_traits<fun>::nargs>::print();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)