命名空间
变体
操作

std::conjunction

来自 cppreference.cn
< cpp‎ | types
 
 
元编程库
类型特性
类型类别
(C++11)
(C++11)(libc++ C++11 模式下不可用)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
类型属性
(C++11)
(C++11)
(C++14)
(C++11)(在 C++26 中已弃用)
(C++11)(在 C++17 中已弃用,直到 C++20*)
(C++11)(在 C++20 中已弃用)
(C++11)
类型特性常量
元函数
conjunction
(C++17)
(C++17)
支持的操作
关系和属性查询
类型修改
(C++11)(C++11)(C++11)
类型转换
(C++11)(在 C++23 中已弃用)
(C++11)(在 C++23 中已弃用)
(C++11)
(C++11)(在 C++17 中已弃用,直到 C++20*)(C++17)

(C++11)
(C++17)
编译时有理算术
编译时整数序列
 
定义于头文件 <type_traits>
template< class... B >
struct conjunction;
(自 C++17 起)

形成类型特征 B...逻辑合取,有效地对特征序列执行逻辑 AND 操作。

特化 std::conjunction<B1, ..., BN> 具有一个公共且明确的基类,即

  • 如果 sizeof...(B) == 0,则为 std::true_type;否则
  • B1, ..., BN 中第一个类型 Bi,对于它 bool(Bi::value) == false,或者如果没有这样的类型,则为 BN

基类的成员名称(除了 conjunctionoperator= 之外)不会被隐藏,并且在 conjunction 中明确可用。

Conjunction 是短路求值的:如果存在模板类型参数 Bi 使得 bool(Bi::value) == false,则实例化 conjunction<B1, ..., BN>::value 不需要实例化 j > iBj::value

如果程序为 std::conjunctionstd::conjunction_v 添加特化,则行为未定义。

内容

[编辑] 模板参数

B... - 每个模板参数 Bi(对于它,Bi::value 被实例化)必须可以用作基类,并定义可转换为 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_typestd::false_type;它仅从第一个 B 继承,其 ::value 显式转换为 bool 后为 false,或者当所有 B 都转换为 true 时,从最后一个 B 继承。 例如,std::conjunction<std::integral_constant<int, 2>, std::integral_constant<int, 4>>::value4

短路实例化将 conjunction折叠表达式区分开来:折叠表达式(如 (... && Bs::value))会实例化 Bs 中的每个 B,而 std::conjunction_v<Bs...> 一旦可以确定值就会停止实例化。 如果后面的类型实例化成本很高,或者使用错误的类型实例化时可能导致硬错误,则这尤其有用。

Feature-test Std Feature
__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)
logical NOT metafunction
(类模板) [编辑]
variadic logical OR metafunction
(类模板) [编辑]