std::experimental::conjunction
来自 cppreference.cn
< cpp | experimental
定义于头文件 <experimental/type_traits> |
||
template< class... B > struct conjunction; |
(library fundamentals TS v2) | |
形成类型特征 B...
的逻辑合取,有效地对特征序列执行逻辑与操作。
特化 std::experimental::conjunction<B1, ..., BN> 具有公共且明确的基类,它是
- 如果 sizeof...(B) == 0,则为 std::true_type;否则
B1, ..., BN
中第一个类型Bi
,其 bool(Bi::value) == false,或者如果没有这样的类型,则为BN
。
基类的成员名称(conjunction
和 operator=
除外)不会被隐藏,并且在 conjunction
中明确可用。
Conjunction 是短路求值的:如果存在一个模板类型参数 Bi
,其 bool(Bi::value) == false,则实例化 conjunction<B1, ..., BN>::value 不需要实例化 Bj::value,其中 j > i。
目录 |
[编辑] 模板参数
B... | - | 每个模板参数 Bi ,对于它 Bi::value 被实例化时,必须可以用作基类并定义可转换为 bool 的成员 value |
[编辑] 助手变量模板
template< class... B > constexpr bool conjunction_v = conjunction<B...>::value; |
(library fundamentals TS v2) | |
[编辑] 可能的实现
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 继承。 例如,conjunction<std::integral_constant<int, 2>, std::integral_constant<int, 4>>::value 是 4。
[编辑] 示例
运行此代码
#include <experimental/type_traits> #include <iostream> // func is enabled if all Ts... have the same type template<typename T, typename... Ts> constexpr std::enable_if_t<std::experimental::conjunction_v<std::is_same<T, Ts>...>> func(T, Ts...) { std::cout << "All types are the same.\n"; } template<typename T, typename... Ts> constexpr std::enable_if_t<!std::experimental::conjunction_v<std::is_same<T, Ts>...>> func(T, Ts...) { std::cout << "Types differ.\n"; } int main() { func(1, 2'7, 3'1); func(1, 2.7, '3'); }
输出
All types are the same. Types differ.
[编辑] 参见
(C++17) |
可变参数逻辑与元函数 (类模板) |