命名空间
变体
操作

std::is_constant_evaluated

来自 cppreference.cn
< cpp‎ | 类型
 
 
 
定义于头文件 <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 constevalstd::is_constant_evaluated通常使用编译器扩展来实现。

特性测试 标准 特性
__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) 指定函数是一个“即时函数”(immediate function),即每次对函数的调用都必须在常量求值中进行[编辑]
constinit 说明符(C++20) 断言变量具有静态初始化,即零初始化常量初始化[编辑]