Search code examples
c++templatesc++11variadic-templatespartial-specialization

Pairwise bool and in c++ template


I am writing a template that takes a arbitrary number of arguments and find the Boolean AND on these value.

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> {}; 

However, I failed to compile by the following message

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

How can I fix this problem?


Solution

  • You have written a re-definition instead of a partial specialization. In order to provide a specialization, you must specify what properties you specialize on.

    This will work:

    #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> {}; 
    //                  ^^^^^^^^^^
    

    As an improvement, think whether you want to support the empty conjunction (typically defined as true). If so, don't specialize on meta_bool_and<bool> but on meta_bool_and<> (derived from std::true_type).