信息发布→ 登录 注册 退出

C++中的std::conjunction和std::disjunction是什么_C++模板逻辑与conjunction/disjunction应用

发布时间:2025-11-08

点击量:
std::conjunction和std::disjunction是C++17提供的编译期逻辑操作工具,分别实现类型 trait 的“与”和“或”判断,支持短路求值,常用于条件启用模板、构建复合类型特征及简化参数包判断。

在C++17中,std::conjunctionstd::disjunction 是两个用于模板元编程的类型特征工具,定义在头文件 aits> 中。它们允许你在编译期对多个布尔类型的模板参数进行逻辑“与”和“或”操作,常用于SFINAE、概念约束(虽然C++20才正式支持concept)以及条件启用函数模板或类模板特化。

std::conjunction:逻辑“与”

std::conjunction 接受一个或多个布尔类型(如 std::true_type 或 std::false_type),如果所有参数都为 true,则结果为 std::true_type;只要有一个为 false,结果就是 std::false_type。

它类似于逻辑中的“与”操作(AND)。其行为是短路的:一旦遇到某个为 false 的类型,后续类型不再被实例化。

示例:

判断多个类型是否都是整数类型:

#include 
#include 

int main() {
    using T1 = int;
    using T2 = long;
    using T3 = double;

    constexpr bool all_integral = std::conjunction_v<
        std::is_integral,
        std::is_integral,
        std::is_integral
    >;

    std::cout << all_integral; // 输出 0,因为 double 不是整型
}

这里使用了 std::conjunction_v,它是 C++17 提供的便捷别名,等价于 std::conjunction<...>::value

std::disjunction:逻辑“或”

std::disjunction 对多个布尔类型执行逻辑“或”操作(OR)。只要有一个为 true,结果就是 std::true_type;仅当全部为 false 时才是 std::false_type。

它也支持短路求值:一旦遇到 true 类型,后续不再实例化。

示例:

判断是否存在某个类型是浮点类型:

#include 
#include 

int main() {
    using T1 = int;
    using T2 = long;
    using T3 = float;

    constexpr bool has_floating = std::disjunction_v<
        std::is_floating_point,
        std::is_floating_point,
        std::is_floating_point
    >;

    std::cout << has_floating; // 输出 1,因为 float 是浮点类型
}

实际应用场景

这两个工具在模板编程中非常有用,尤其是在需要组合多个条件来控制函数重载或类特化时。

1. 条件启用函数模板

结合 std::enable_if_t 使用,可以限制模板参数满足多个或任一条件:

template
std::enable_if_t,
    std::is_same,
    std::is_same
>, void>
process(T value) {
    // 只允许 int、float、double 类型调用
}

2. 自定义类型特征

你可以用 conjunction 构建复合类型特征:

template
struct is_valid_number : std::conjunction<
    std::is_arithmetic,
    std::negation>
> {};

这个特征表示“是算术类型但不是布尔类型”。

3. 避免编译错误

在模板参数包展开时,可以用 disjunction 实现“是否存在某种类型”的判断,避免对每个类型做复杂递归处理。

基本上就这些。std::conjunction 和 std::disjunction 让你在编译期做逻辑判断更简洁、高效,是现代C++模板编程的重要组成部分。
标签:# 布尔类型  # 是在  # 都是  # 中非  # 可以用  # 你在  # 浮点  # 特化  # 布尔  # 多个  # 函数重载  # 工具  # 整数类型  # 类模板  # 函数模板  # 递归  # 编译错误  # stream  # ios  # c++  # ai  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!