使用非常量表达式作为模板参数 [英] Using non-const expression as template parameter
本文介绍了使用非常量表达式作为模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个结构来访问可变参数模板的参数:
I have this struct to access the arguments of a variadic template:
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;
};
};
然后我用
typedef function<void(Args...)> fun;
std::cout << std::is_same<int, typename function_traits<fun>::template arg<0>::type>::value << std::endl;
但是,我想遍历参数以能够处理任意数量的参数。下面的方法不起作用,但是为了说明我想要的内容:
However, I would like to iterate through the arguments to be able to handle an arbitrary number of arguments. The following doesn't work, but to illustrate what I want:
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();
}
这篇关于使用非常量表达式作为模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文