C++20新特性_std::is_constant_evaluated() 编译期判断

文章目录

  • [第二章 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 的灵活性,让开发者可以编写出在不同求值阶段都能以最优方式执行的统一接口。

相关推荐
Mr_WangAndy3 小时前
C++23新特性_多维下标运算符
c++·c++23·c++40周年·多维下标运算符
Mr_WangAndy3 小时前
C++23新特性_#warning 预处理指令
c++·c++23·c++40周年·c++23新特性·warning预处理命令
Mr_WangAndy4 小时前
C++23新特性_Deducing this
c++23·c++40周年·deducingthis
Mr_WangAndy4 小时前
C++23新特性_if consteval
c++·c++23·c++40周年·if consteval
小毅&Nora20 小时前
【后端】【C++】从裸指针到 C++20 协程:现代 C++ 内存与并发编程的双重革命
java·c++20
Mr_WangAndy1 天前
C++20新特性_std::jthread和chrono库扩展
c++20·c++20新特性·c++40周年·chrono库扩展·jthread线程
Mr_WangAndy1 天前
C++20新特性_原子智能指针,std::source_location和位操作函数
c++20·c++40周年·c++原子智能指针·source_location·位操作函数
Mr_WangAndy1 天前
C++20新特性_[[likely]] , [[unlikely]]属性和特性测试宏
c++20·likely·c++40周年·unlikely·特性测试宏
Mr_WangAndy1 天前
C++20新特性_std::format和span
c++20·format·c++20新特性·span·c++40周年