我正在编写一个模板,它接受任意数量的参数并在这些值上找到布尔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> {};
我该如何解决这个问题?
您已经编写了重新定义而不是部分专业化。要提供专业化,您必须指定您专注的属性。
这将有效:
#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<bool>
,而是专注于meta_bool_and<>
(来自std::true_type
)。
作为替代方案,您可以编写它:
template <bool ... Bs>
using meta_bool_and = std::is_same<std::integral_sequence<bool, true, Bs...>,
std::integral_sequence<bool, Bs..., true>>;
或者在c ++ 17中:
template <bool ... Bs>
using meta_bool_and = std::integral_constant<bool, (Bs && ...)>;
由于这些是专业化,因此需要声明它们。您也可以将其中一个作为基本案例
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 ^^^