c++ - 使用非常量表达式作为模板参数

标签 c++ c++11 function-pointers functor variadic-templates

这是对 How do I get the argument types of a function pointer in a variadic template class? 的跟进

我有这个结构来访问可变参数模板的参数:

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();
}

关于c++ - 使用非常量表达式作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9077612/

相关文章:

c++ - 似乎无法在 main 中调用一个类

c++ - C++中错误的计算方法

c++ - 为什么 ostream 不能转换为 ostream?

c++ - 使用部分类型知识访问模板的参数

c++ - 如何将函数作为参数从 C 传递给 C++,然后返回给 C

c++ - 如何使用 OpenSSL 1.1.0 验证主机名?

c++ - 确定最佳线程数

c++ - 初始化扩展数组元素

c++ - 指向实例成员的函数指针

c++ - 在 C++ 中,是否有一种最佳方式来运行指向该值的指针链?