【问题标题】:Using non-const expression as template parameter使用非常量表达式作为模板参数
【发布时间】:2012-02-23 01:23:49
【问题描述】:

这是对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;
}

【问题讨论】:

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


    【解决方案1】:

    您需要按照以下方式进行编译时迭代

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

    【讨论】:

    • 谢谢你,@Mike。我想,它一定是递归的,在编译时,我只是没能把它放在一起;)但是:fun 在范围内是未知的。我试图将fun 作为模板参数传递,但在专业化中,编译器抱怨function template partial specialization ‘print&lt;0, fun&gt;’ is not allowed。我的专业是:template &lt;typename fun&gt; void print&lt;0,fun&gt;() {}
    • @steffen:不,您不能部分专门化函数模板,只能专门化类模板。我想您需要将函数包装在类中;我会更新答案。
    • 美丽、完美的解决方案!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多