std::conjunction
來自 cppreference.com
定義於標頭檔案 <type_traits> |
||
template< class... B > struct conjunction; |
(C++17 起) | |
形成型別特徵 B... 的邏輯合取,有效地對特徵序列執行邏輯 AND。
特化 std::conjunction<B1, ..., BN> 具有一個公共且明確的基類,它或者是
- 若 sizeof...(B) == 0,則為 std::true_type;否則為
- B1, ..., BN 中第一個使得 bool(Bi::value) == false 的型別
Bi
,或在沒有此類型別時為BN
。
基類的成員名,除了 conjunction
和 operator=
外,不會被隱藏,並且在 conjunction
中可明確使用。
Conjunction 是短路求值的:如果存在一個模板型別引數 Bi
,其 bool(Bi::value) == false,則例項化 conjunction<B1, ..., BN>::value 不需要例項化 j > i
的 Bj::value。
如果程式為 std::conjunction
或 std::conjunction_v
新增特化,則行為是未定義的。
目錄 |
[編輯] 模板引數
B... | - | 對於每個例項化了 Bi::value 的模板引數 Bi ,它必須可用作基類,並定義一個可轉換為 bool 的成員 value |
[編輯] 輔助變數模板
template< class... B > constexpr bool conjunction_v = conjunction<B...>::value; |
(C++17 起) | |
[編輯] 可能的實現
template<class...> struct conjunction : std::true_type {}; template<class B1> struct conjunction<B1> : B1 {}; template<class B1, class... Bn> struct conjunction<B1, Bn...> : std::conditional_t<bool(B1::value), conjunction<Bn...>, B1> {}; |
[編輯] 注意
conjunction
的特化不一定繼承自 std::true_type 或 std::false_type:它簡單地繼承自第一個 B
,其 ::value
顯式轉換為 bool 為 false,或者當所有 B
都轉換為 true 時,繼承自最後一個 B
。例如,std::conjunction<std::integral_constant<int, 2>, std::integral_constant<int, 4>>::value 是 4。
短路例項化將 conjunction
與摺疊表示式區分開來:摺疊表示式,如 (... && Bs::value),會例項化 Bs
中的每個 B
,而 std::conjunction_v<Bs...> 一旦值可以確定就會停止例項化。這在後續型別例項化成本很高或在用錯誤型別例項化時可能導致硬錯誤的情況下特別有用。
特性測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_lib_logical_traits |
201510L |
(C++17) | 邏輯運算子型別特性 |
[編輯] 示例
執行此程式碼
#include <iostream> #include <type_traits> // func is enabled if all Ts... have the same type as T template<typename T, typename... Ts> std::enable_if_t<std::conjunction_v<std::is_same<T, Ts>...>> func(T, Ts...) { std::cout << "All types in pack are the same.\n"; } // otherwise template<typename T, typename... Ts> std::enable_if_t<!std::conjunction_v<std::is_same<T, Ts>...>> func(T, Ts...) { std::cout << "Not all types in pack are the same.\n"; } template<typename T, typename... Ts> constexpr bool all_types_are_same = std::conjunction_v<std::is_same<T, Ts>...>; static_assert(all_types_are_same<int, int, int>); static_assert(not all_types_are_same<int, int&, int>); int main() { func(1, 2, 3); func(1, 2, "hello!"); }
輸出
All types in pack are the same. Not all types in pack are the same.
[編輯] 參見
(C++17) |
邏輯 NOT 元函式 (類模板) |
(C++17) |
可變引數邏輯 OR 元函式 (類模板) |