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

在C++17中,std::conjunction 和 std::disjunction 是两个用于模板元编程的类型特征工具,定义在头文件 <type_traits> 中。它们允许你在编译期对多个布尔类型的模板参数进行逻辑“与”和“或”操作,常用于SFINAE、概念约束(虽然C++20才正式支持concept)以及条件启用函数模板或类模板特化。
std::conjunction<T...> 接受一个或多个布尔类型(如 std::true_type 或 std::false_type),如果所有参数都为 true,则结果为 std::true_type;只要有一个为 false,结果就是 std::false_type。
它类似于逻辑中的“与”操作(AND)。其行为是短路的:一旦遇到某个为 false 的类型,后续类型不再被实例化。
示例:判断多个类型是否都是整数类型:
立即学习“C++免费学习笔记(深入)”;
#include <type_traits>
#include <iostream>
int main() {
using T1 = int;
using T2 = long;
using T3 = double;
constexpr bool all_integral = std::conjunction_v<
std::is_integral<T1>,
std::is_integral<T2>,
std::is_integral<T3>
>;
std::cout << all_integral; // 输出 0,因为 double 不是整型
}
这里使用了 std::conjunction_v,它是 C++17 提供的便捷别名,等价于 std::conjunction<...>::value。
std::disjunction<T...> 对多个布尔类型执行逻辑“或”操作(OR)。只要有一个为 true,结果就是 std::true_type;仅当全部为 false 时才是 std::false_type。
它也支持短路求值:一旦遇到 true 类型,后续不再实例化。
示例:判断是否存在某个类型是浮点类型:
#include <type_traits>
#include <iostream>
int main() {
using T1 = int;
using T2 = long;
using T3 = float;
constexpr bool has_floating = std::disjunction_v<
std::is_floating_point<T1>,
std::is_floating_point<T2>,
std::is_floating_point<T3>
>;
std::cout << has_floating; // 输出 1,因为 float 是浮点类型
}
这两个工具在模板编程中非常有用,尤其是在需要组合多个条件来控制函数重载或类特化时。
1. 条件启用函数模板
结合 std::enable_if_t 使用,可以限制模板参数满足多个或任一条件:
template<typename T>
std::enable_if_t<std::disjunction_v<
std::is_same<T, int>,
std::is_same<T, float>,
std::is_same<T, double>
>, void>
process(T value) {
// 只允许 int、float、double 类型调用
}
2. 自定义类型特征
你可以用 conjunction 构建复合类型特征:
template<typename T>
struct is_valid_number : std::conjunction<
std::is_arithmetic<T>,
std::negation<std::is_same<T, bool>>
> {};
这个特征表示“是算术类型但不是布尔类型”。
3. 避免编译错误
在模板参数包展开时,可以用 disjunction 实现“是否存在某种类型”的判断,避免对每个类型做复杂递归处理。
基本上就这些。std::conjunction 和 std::disjunction 让你在编译期做逻辑判断更简洁、高效,是现代C++模板编程的重要组成部分。以上就是C++中的std::conjunction和std::disjunction是什么_C++模板逻辑与conjunction/disjunction应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号