Is there a reason to use std::conjunction/std::disjunction instead of a fold expression over “&&”/”||”?

std::conjunction short-circuits ::value instantiation, while the fold expression doesn’t. This means that, given:

template <typename T> 
struct valid_except_void : std::false_type { };

template <> 
struct valid_except_void<void> { };

The following will compile:

template <typename... Ts>
constexpr auto test = std::conjunction_v<valid_except_void<Ts>...>;

constexpr auto inst = test<int, void>;

But the following won’t:

template <typename... Ts>
constexpr auto test = (valid_except_void<Ts>::value && ...);

constexpr auto inst = test<int, void>;

live example on godbolt.org


From cppreference:

Conjunction is short-circuiting: if there is a template type argument Bi with bool(Bi::value) == false, then instantiating conjunction<B1, ..., BN>::value does not require the instantiation of Bj::value for j > i.

Leave a Comment

tech