【发布时间】: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 下的汇编结果确认它在编译时执行。这是一种处理小事的方法,但我仍然会感谢其他一些方法。
【问题讨论】:
-
只需声明
globalArrayconstexpr。只有constexpr函数也需要在运行时调用。不过,constexpr变量必须是编译时常量。 -
我认为cppreference注释下的第一段很有帮助。
标签: c++ constexpr functor compile-time