nknight nknight - 3 months ago 16
C++ Question

C++ Variadic template AND and OR

Can you use C++11 variadic templates to complete

/* ??? */
in:

template<bool...v> struct var_and { static bool constexpr value = /* ??? */; };


so that
var_and<v...>::value
provides
&&
over the boolean pack
v
at compile-time?

Can you do the same for
struct var_or<v...>
for
||
?

Can you use short-circuit evaluation (in both cases)?

Answer

You don't want value to be a typedef.

template<bool head, bool... tail>
struct var_and {
    static constexpr bool value = head && var_and<tail...>::value;
};

template<bool b> struct var_and<b> {
    static constexpr bool value = b;
};

Obviously the same can be done for ||.

Short circuit evaluation doesn't matter because this only deals with constant expressions which won't have any side effects.

Here's another method which stops recursively generating types as soon as it find a false value, emulating a kind of short circuiting:

template<bool head, bool... tail>
struct var_and { static constexpr bool value = false; };

template<bool... tail> struct var_and<true,tail...> {
    static constexpr bool value = var_and<tail...>::value;
};

template<> struct var_and<true> {
    static constexpr bool value = true;
};
Comments