如何确认我的constexpr表达式实际上已经在编译时执行

How can I confirm that my constexpr expression has been actually performed in compile-time

本文关键字:实际上 编译 执行 表达式 constexpr 何确认 确认 我的      更新时间:2023-10-16

由于constexpr不能保证它会在"编译时"处理,我想知道一些方法来检查我的代码是否真的在编译时执行。

假设我已经创建了一些函子类,该类在执行时返回一个值数组。我希望它在编译时进行。

#include "Functor.hpp"
constexpr Functor<int> functor_g; // not sure if should be static too
auto globalArray = functor_g(); // not sure if should be also const/constexpr
int main()
{
// ...
}

显然,我不能在这里运行任何计时器,因为它们需要运行时环境。

编辑:我已经通过检查godbolt.org下的汇编结果确认了它在编译时的性能。这是一种小事情的方法,但我仍然会感谢其他一些方法。

如何确认我的constexpr表达式实际上已在编译时中执行

您必须检查生成的程序集。

但您只能使用特定平台中的特定编译器来检查特定的可执行文件。对于不同的编译器,您无法保证从相同的代码中获得编译时执行。

从语言的角度来看,您可以强制执行编译时,但永远不要忘记"好像规则",即"允许任何和所有不改变程序可观察行为的代码转换"。

要强制执行编译时(忽略"好像规则"(,必须使用constexpr函数返回的值,其中需要一个值。

一些示例(假设constexpr foo()函数返回std::size_t(:

1( 初始化constexpr变量

constexpr std::size_t bar = foo();

2( 在C型阵列大小的中

char bar[foo()];

3( 在模板参数中

std::array<char, foo()>  bar;

4( 在static_assert()测试中

static_assert( foo() == 3u, "isn't three");