C++ 使用非常量表达式作为模板参数
这是一个后续行动 我使用此结构访问可变模板的参数:C++ 使用非常量表达式作为模板参数,c++,c++11,function-pointers,functor,variadic-templates,C++,C++11,Function Pointers,Functor,Variadic Templates,这是一个后续行动 我使用此结构访问可变模板的参数: 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); typed
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;
};
};
模板
结构功能特征;
模板
结构功能特性
{
静态常数size\u t nargs=sizeof…(Args);
typedef R result_type;
模板
结构参数
{
typedef typename std::tuple_元素::type type;
};
};
我使用
typedef function<void(Args...)> fun;
std::cout << std::is_same<int, typename function_traits<fun>::template arg<0>::type>::value << std::endl;
typedef函数乐趣;
std::cout您需要按照
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();
}
template struct print\u helper{
静态无效打印(){
print_helper::print();
std::我不能谢谢你,@Mike。我想,它一定是递归的,在编译时,我只是没有把它放在一起;)但是:fun
在范围内是未知的。我试图将fun
作为模板参数传递,但在专门化过程中,编译器抱怨,函数模板部分专门化“print”是not允许
。我的专业是:template void print(){}
@steffen:不,你不能部分专业化函数模板,只能专业化类模板。我想你需要将函数封装在类中;我会更新答案。漂亮、完美的解决方案!谢谢!
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();
}