c++ - 是否可以测试 constexpr 函数是否在编译时求值?

标签 c++ c++14 c++17 constexpr compile-time

自从 constexpr 的扩展版本(我认为是从 C++14 开始)以来,您可以声明 constexpr 函数,这些函数可以用作“真实的” constexpr。也就是说,代码在编译时执行,或者可以作为内联函数运行。那么什么时候可以有这个程序:

#include <iostream>

constexpr int foo(const int s) {
  return s + 4;
}

int main()
{
    std::cout << foo(3) << std::endl;

    const int bar = 3;
    std::cout << foo(bar) << std::endl;

    constexpr int a = 3;
    std::cout << foo(a) << std::endl;

    return 0;
}

结果是:

7
7
7

到目前为止一切顺利。

有没有办法(可能是标准的)在 foo(const int s) 内部知道函数是在编译时还是在运行时执行?

编辑:还有可能在运行时知道函数是否在编译时求值吗?

最佳答案

C++20 引入了 is_constant_evaluated ,在 header 中定义 <type_traits> ,它解决了这个问题。

constexpr int foo(int s)
{
    if (std::is_constant_evaluated()) // note: not "if constexpr"
        /* evaluated at compile time */;
    else
        /* evaluated at run time */;
}

注意这里是普通的if使用而不是 if constexpr .如果你使用 if constexpr ,那么必须在编译时评估条件,所以 is_constant_evaluated始终返回 true,使测试无用。

关于c++ - 是否可以测试 constexpr 函数是否在编译时求值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47801134/

相关文章:

c++ - 如何在 C++ 中将局部变量转换为指针?

c++ - 使用 opencv mog 检测器和 c++ 从实时摄像机馈送中进行背景减法

c++ - 将一系列 h264 帧写入多个文件

c++ - 与 MSVC 的链接错误,但与带有 constexpr 的 g++ 的链接错误

c++ - 为什么 C++17 中的 std::variant 允许 std::variant<int, const int>

c++ - 如何通过链接器脚本将符号放置在特定地址?

c++ - Boost spirit x3 解析器不适用于多个属性

c++ - 删除了默认构造函数。仍然可以创建对象......有时

c++ - 防止 C++14 中的左值实例化

c++ - 如果 `std::optional` 存在则条件编译函数