文章目录
- [第二章 C++20标准库特性](#第二章 C++20标准库特性)
-
- [2.8 std::is_constant_evaluated() 编译器判断](#2.8 std::is_constant_evaluated() 编译器判断)
本文记录C++20新特性之std::is_constant_evaluated() 。
第二章 C++20标准库特性
2.8 std::is_constant_evaluated() 编译器判断
C++20引入了std::is_constant_evaluated(),包含在头文件<type_traits>中,主要作用判断当前函数调用是否正在一个编译期间常量上下文中执行。
如果是在编译期求值(例如,在初始化 constexpr 变量、static_assert 中,或在 consteval 函数内),返回 true。
如果是在运行时求值,返回 false。
这个函数引入的核心价值在于,允许我们编写一个既能用于编译期也能用于运行时的 constexpr 函数,并为这两种情况提供不同的实现路径。这解决了 constexpr 函数的一个痛点:有些操作(如调用非 constexpr 的库函数、I/O 操作)在运行时是允许的,但在编译期是禁止的。
下面实现一个更智能的 power函数:
cpp
constexpr double power(double base, int exp)
{
// 检查当前调用是否在编译期常量上下文中
if (std::is_constant_evaluated())
{
// 编译期路径:使用简单的循环
// 这个实现对编译器友好
double res = 1.0;
for (int i = 0; i < exp; ++i) {
res *= base;
}
return res;
}
else
{
// 运行时路径:调用标准库中更高效的函数
// std::pow 不是 constexpr,所以不能在编译期路径中使用
return std::pow(base, exp);
}
}
void test()
{
// 1 编译期求值
// 一个constexpr ,所以会在编译期计算
constexpr double compiled_result = power(2.0, 10);
cout << "Compiled Result: " << compiled_result << endl;
static_assert(compiled_result == 1024.0,"非编译期间计算");
// 2 运行时求值
double runtime_base = 2.0;
int runtime_exp = 10;
double runtime_result = power(runtime_base, runtime_exp);
cout << "Runtime Result: " << runtime_result << endl;
}
test() 函数分别演示了在编译期(初始化 constexpr 变量)和运行时调用 power 函数的场景。通过这种方式,std::is_constant_evaluated() 极大地增强了 constexpr 的灵活性,让开发者可以编写出在不同求值阶段都能以最优方式执行的统一接口。