std::is_constant_evaluated
来自 cppreference.cn
定义于头文件 <type_traits> |
||
constexpr bool is_constant_evaluated() noexcept; |
(自 C++20 起) | |
检测函数调用是否发生在常量求值语境中。如果调用的求值发生在显式常量求值的表达式或转换的求值中,则返回 true;否则返回 false。
为了确定以下变量的初始化器是否为显式常量求值,编译器可能首先执行一次尝试性常量求值
- 具有引用类型或 const 限定的整型或枚举类型的变量;
- 静态和线程局部变量。
不建议在这种情况下依赖结果。
int y = 0; const int a = std::is_constant_evaluated() ? y : 1; // Trial constant evaluation fails. The constant evaluation is discarded. // Variable a is dynamically initialized with 1 const int b = std::is_constant_evaluated() ? 2 : y; // Constant evaluation with std::is_constant_evaluated() == true succeeds. // Variable b is statically initialized with 2
内容 |
[编辑] 参数
(无)
[编辑] 返回值
如果调用的求值发生在显式常量求值的表达式或转换的求值中,则为 true;否则为 false。
[编辑] 可能的实现
// This implementation requires C++23 if consteval. constexpr bool is_constant_evaluated() noexcept { if consteval { return true; } else { return false; } } |
[编辑] 注解
当直接用作 static_assert 声明或 constexpr if 语句的条件时,std::is_constant_evaluated() 始终返回 true。
因为 C++20 中缺少 if consteval,所以 std::is_constant_evaluated
通常使用编译器扩展来实现。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_is_constant_evaluated |
201811L |
(C++20) | std::is_constant_evaluated
|
[编辑] 示例
运行此代码
#include <cmath> #include <iostream> #include <type_traits> constexpr double power(double b, int x) { if (std::is_constant_evaluated() && !(b == 0.0 && x < 0)) { // A constant-evaluation context: Use a constexpr-friendly algorithm. if (x == 0) return 1.0; double r {1.0}; double p {x > 0 ? b : 1.0 / b}; for (auto u = unsigned(x > 0 ? x : -x); u != 0; u /= 2) { if (u & 1) r *= p; p *= p; } return r; } else { // Let the code generator figure it out. return std::pow(b, double(x)); } } int main() { // A constant-expression context constexpr double kilo = power(10.0, 3); int n = 3; // Not a constant expression, because n cannot be converted to an rvalue // in a constant-expression context // Equivalent to std::pow(10.0, double(n)) double mucho = power(10.0, n); std::cout << kilo << " " << mucho << "\n"; // (3) }
输出
1000 1000
[编辑] 参见
constexpr 说明符(C++11) |
指定变量或函数的值可以在编译时计算 |
consteval 说明符(C++20) |
指定函数为立即函数,即对该函数的每次调用都必须在常量求值中 |
constinit 说明符(C++20) |
断言变量具有静态初始化,即零初始化和常量初始化 |