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

时间:2016-10-06 07:05:55

标签: 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(或者在编译时上下文中,如模板参数或enum shenanigans)?

这样的事情:

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; }

1 个答案:

答案 0 :(得分:5)

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

template <int N> constexpr int force_compute_at_compile_time();

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

由于N是模板参数,因此 是一个常量表达式。

相关问题