【问题标题】:Pairwise bool and in c++ template成对 bool 和 c++ 模板
【发布时间】:2016-05-10 20:14:43
【问题描述】:

我正在编写一个模板,它接受任意数量的参数并在这些值上找到布尔 AND。

template <bool... Vs> struct meta_bool_and;

template <bool V> struct meta_bool_and : std::integral_constant<bool, V> {}; 

template <bool V, bool... Vs> 
struct meta_bool_and : std::integral_constant<bool, V && meta_bool_and<Vs...>::value> {}; 

但是,我通过以下消息编译失败

 error: redeclared with 2 template parameters
 struct meta_bool_and : std::integral_constant<bool, V && meta_bool_and<Vs...>::value> {}; 

我该如何解决这个问题?

【问题讨论】:

    标签: c++ templates c++11 variadic-templates partial-specialization


    【解决方案1】:

    你也可以这样写:

    template <bool ... Bs>
    using meta_bool_and = std::is_same<std::integer_sequence<bool, true, Bs...>,
                                       std::integer_sequence<bool, Bs..., true>>;
    

    或在 c++17 中:

    template <bool ... Bs>
    using meta_bool_and = std::integral_constant<bool, (Bs && ...)>;
    

    【讨论】:

    • 第一个很聪明。对我来说几乎太聪明了……
    • std::integral_sequence ?你是说std::integer_sequence 吗?
    • @largest_prime_is_463035818:错字已修复,谢谢。
    【解决方案2】:

    您编写了重新定义而不是部分特化。为了提供专业化,您必须指定您专注于哪些属性。

    这将起作用:

    #include <type_traits>
    
    template <bool... Vs> struct meta_bool_and;
    
    template <bool V> struct meta_bool_and<V> : std::integral_constant<bool, V> {};
    //                                    ^^^
    
    template <bool V, bool... Vs> 
    struct meta_bool_and<V, Vs...> : std::integral_constant<bool, V && meta_bool_and<Vs...>::value> {}; 
    //                  ^^^^^^^^^^
    

    作为一种改进,考虑是否要支持空连词(通常定义为 true)。如果是这样,不要专注于meta_bool_and&lt;bool&gt;,而是专注于meta_bool_and&lt;&gt;(源自std::true_type)。

    【讨论】:

      【解决方案3】:

      由于这些是特化,因此需要这样声明。您也可以将其中一个作为基本案例

      template <bool V, bool... Vs>
      struct meta_bool_and : std::integral_constant<bool, V && meta_bool_and<Vs...>::value> {};
      // made base case
      
      template <bool V>
      struct meta_bool_and<V> : std::integral_constant<bool, V> {};
      // specialization   ^^^
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-11
        • 1970-01-01
        • 2010-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多