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

相关推荐
啟明起鸣6 天前
【C++20新特性】概念约束特性与 “模板线程池”,概念约束是为了 “把握未知对象”
开发语言·c++·c++20·模板线程池
linweidong6 天前
虎牙C++面试题及参考答案(上)
stl·vector·线程·内存管理·c++20·c++面试·c++调用
吐泡泡_7 天前
C++20(概念和约束)
c++20
訫悦11 天前
体验在Qt中简单使用C++20的协程
qt·c++20·协程
fpcc14 天前
C++20中的预处理器宏——__VA_OPT__
c++20
Codeking__17 天前
C++20的consteval和constinit(接C++11的constexpr)
算法·c++20
六bring个六19 天前
C++20协程
c++20·协程
C++实习生19 天前
Visual C++ 2005 Express 中文版
express·c++20
Ethan Wilson21 天前
VS2019 C++20 模块相关 C1001: 内部编译器错误
开发语言·c++·c++20
DYS_房东的猫21 天前
《 C++ 零基础入门教程》第10章:C++20 核心特性 —— 编写更现代、更优雅的 C++
java·c++·c++20