【问题标题】:How can I confirm that my constexpr expression has been actually performed in compile-time [duplicate]如何确认我的 constexpr 表达式实际上已在编译时执行 [重复]
【发布时间】:2020-02-23 09:17:32
【问题描述】:

由于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 下的汇编结果确认它在编译时执行。这是一种处理小事的方法,但我仍然会感谢其他一些方法。

【问题讨论】:

标签: c++ constexpr functor compile-time


【解决方案1】:

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

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

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

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

要强制执行编译时执行(忽略“as-if 规则”),您必须使用从 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");

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2015-02-22
    • 2012-12-27
    相关资源
    最近更新 更多