1

Ich schreibe eine Vorlage, die eine beliebige Anzahl von Argumenten und suchen Sie das Boolesche AND auf diesen Wert.Pairwise Bool und in C++ Vorlage

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

Jedoch konnte ich durch die folgende Meldung

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

So übersetzen kann ich dieses Problem beheben?

Antwort

4

Sie haben anstelle einer Teilspezialisierung eine Neudefinition geschrieben. Um eine Spezialisierung bereitzustellen, müssen Sie angeben, auf welche Eigenschaften Sie spezialisiert sind.

wird diese Arbeit:

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

Als Verbesserung überlegen, ob Sie die leere Verbindung (in der Regel definiert als true) unterstützen wollen. Wenn ja, spezialisieren Sie sich nicht auf meta_bool_and<bool>, sondern auf meta_bool_and<> (abgeleitet von std::true_type).

1

Da dies Spezialisierungen sind, müssen sie als solche deklariert werden. Sie können auch eine der Basisfall

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 ^^^ 
5

Als Alternativen machen, können Sie es schreiben kann:

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

oder in C++ 1z:

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

Die erste ist sehr klug. Fast zu schlau für mich ... – 5gon12eder