【问题标题】:Should I prefer to call template metafunctions through a nested typedef or inheritance?我应该更喜欢通过嵌套的 typedef 还是继承来调用模板元函数?
【发布时间】:2013-11-11 14:41:01
【问题描述】:

我可以编写一个递归的Contains 元函数,通过继承或嵌套的typedef 调用自身。以下标准有何不同(如果有)?

A:编译时需要的编译时间和内存。

B:最大递归限制(一个允许我使用比另一个更多的参数吗?)

C:惰性实例化(允许我省略更多实例化吗?这在当前示例中可能没有什么不同。但是,如果一个类嵌套了 std::conditional 的 typedef 而不是从它派生的?)

1:

template<typename T, typename... Ts>
struct Contains : std::false_type {};       //only possible if Ts is empty so does not contain
template<typename T, typename U, typename... Ts>
struct Contains<T, U, Ts...> : Contains<T, Ts...>{};
template<typename T, typename... Ts>
struct Contains<T, T, Ts...> : std::true_type{};

2:

template<typename T, typename... Ts>
struct Contains {
    typedef std::false_type Type;
};      //only possible if Ts is empty so does not contain
template<typename T, typename U, typename... Ts>
struct Contains<T, U, Ts...> {
    typedef typename Contains<T, Ts...>::Type Type;
};
template<typename T, typename... Ts>
struct Contains<T, T, Ts...>{
    typedef std::true_type Type;
};

【问题讨论】:

    标签: c++ templates c++11 recursion metaprogramming


    【解决方案1】:

    我会使用继承,原因是它自然允许标签调度:

    template <typename T>
    void f_impl(T const & t, std::true_type derivedB) { ... }
    ...
    template <typename T>
    void f(T const & t) {
       f_impl(t, is_base_of<B,T>());
    }
    

    同时继承可用于插入嵌套信息,在本例中为::value静态成员,其计算结果为true

    【讨论】:

    • 好主意,我没想到。您知道 MSVC 和 GCC 的最大递归深度是否存在差异?即,如果我用 500 或 1000 个参数调用包含,它们会以不同的最大数量失败吗?
    • @PorkyBrain:标准中没有定义这些限制,我也不知道。但它们应该在供应商的文档中可用。特别是对于 gcc(我比 VS 更熟悉 gcc)你可以用-ftemplate-depth 控制它,虽然我从来没有用过。
    猜你喜欢
    • 2013-12-13
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2011-11-29
    相关资源
    最近更新 更多