std::conjunction
来自 cppreference.cn
定义于头文件 <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 元函数 (类模板) |