簡體   English   中英

標准庫中std :: disjunction的實現

[英]Implementation of std::disjunction in the Standard Library

我已經在標准庫( 源代碼 )中看到了std::disjunction的實現:

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

您返回std::integral_constant

std::disjunction返回給定類型之一(可能具有其他成員)。

此外,如果所有對象都是偽造的disjunction<B1,...,BN>則要求disjunction<B1,...,BN>會導致最后一個給定類型( BN )(請參閱[meta.ologic#10.2] )。

一元特化disjunction<B1>在遞歸序列的disjunction<B1>實現此行為。

例如,如果沒有一元專門化,則如果B1::valuetrue ,則disjunction<B1>將給出B1 ,否則為std::false_type


由於所有B可能具有不同的類型,因此std :: disjunction返回其:: value成員轉換為true的第一個類型。 有點奇怪嗎? 制作一個有趣的選擇器可能會很有用

的確,我還從未使用過這個特征家族(至今),但是它似乎是一個靈活的抽象:

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

我唯一討厭分離的是它的名字...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM