std::disjunction 在标准库中的实现

Implementation of std::disjunction in the Standard Library

我看过 std::disjunction in the Standard Library (source):

的实现
template<class...> struct disjunction : std::false_type { };
template<class B1> struct disjunction<B1> : B1 { };
template<class B1, class... Bn>
struct disjunction<B1, Bn...>
    : std::conditional_t<bool(B1::value), B1, disjunction<Bn...>> { };

我很好奇需要将 disjunction<B1> 专门化为 B1。为什么它比我天真的实现更好?

template<class...>              struct or_t
    : std::false_type {};
template<class B1, class... Bn> struct or_t<B1, Bn...>
    : std::integral_constant<bool, bool(B1::value) || bool(or_t<Bn...>::value)> {};

你returnstd::integral_constant.

std::disjunction returns 给定类型之一(可能有其他成员)。

此外,如果所有类型都是假的(请参阅 [meta.logical#10.2]),则需要 disjunction<B1,...,BN> 导致最后给定的类型(BN)。

一元特化 disjunction<B1> 在递归序列的尾部实现此行为。

例如,如果没有一元特化,如果 B1::valuetruedisjunction<B1> 将给出 B1,否则 std::false_type


Since all Bs might have different types, std::disjunction returns the first type whose ::value member converts to true. Isn't that a bit strange? It might be useful to make a funny selector

的确,我(还)从未使用过这一系列特征,但它似乎是一个相当灵活的抽象:

template<class T>
struct some_condition: std::bool_constant</*whatever*/>
{
  using payload = T;
};

// take the first T satisfying some_condition, or last T if none does
disjunction<some_condition<T>...>::payload

// take the first T satisfying some_condition, or none
disjunction<some_condition<T>...,none_type>::payload

我唯一讨厌 disjunction 的是它的名字...