c++ - 如何强制在编译时评估 constexpr 函数

标签 c++ c++11 constexpr

<分区>

给定以下代码:

constexpr int omg() { return 42; }

const int a = omg(); // NOT guaranteed to be evaluated at compile time

constexpr const int a = omg(); // guaranteed to be evaluated at compile time

有没有办法强制在编译时评估某些东西而不将其分配给某些 constexpr(或在编译时上下文中,如模板参数或枚举恶作剧)?

像这样:

const int a = force_compute_at_compile_time(omg());

也许是这样的(它不能编译——我对 constexpr 还不是很了解):

template<typename T> constexpr T force_compute_at_compile_time(constexpr const T& a) { return a; }

最佳答案

你可以使用非类型模板参数:

template <int N> constexpr int force_compute_at_compile_time();

const int a = force_compute_at_compile_time<omg()>();

因为 N 是一个模板参数,它必须是一个常量表达式。

关于c++ - 如何强制在编译时评估 constexpr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39889604/

相关文章:

c++ - 在 linux 下,在 C++ 中使用 system() 执行命令的转义序列

c++ - 从另一个虚函数调用时内联虚函数?

c++ - 使用用户定义的转换运算符的函数模板重载决议

c++ - 使用 std::atomic 实现无锁结构,Dtor 崩溃

c++ - 如何推断 C++11 中的模板参数类型?

c++ - 如何使用 SIFT 特征/描述符作为 SVM 训练的输入?

c++ - 设置当前驱动器?时间:2019-03-17 标签:c++win32

c++ - 有没有一种很好的方法来实现具有默认失败情况的条件类型?

c++ - constexpr 构造函数在 GCC 在编译时评估时给出不同的结果

c++ - 当您可以从consteval函数创建constexpr对象时,为什么constexpr函数不能消耗consteval函数?