如何强制constexpr函数在编译时求值
How to force a constexpr function to be evaluated at compile time
给定以下代码:
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++项目编译强制使用 /clr 选项,尽管在没有公共语言运行时支持的情况下执行它
- C++根据调用的构造函数强制编译时错误
- 静态类型是在编译时还是运行时强制实施的?
- 强制在编译时计算类的类的常量成员
- 在 sizeof 运算符上强制编译时错误
- 错误 : 尚无法编译此意外的强制转换值
- 编译错误 QT - 无法从类型强制转换
- 如何在 constexpr 函数中强制编译错误,而不是让它衰减到非 constexpr 上下文中?
- 模板化类 - 在不支持的类上强制编译错误
- 我可以强制C++类使用最小的空间进行编译吗?
- 为非专用模板实例化强制执行编译错误
- 在头强制重新编译中定义的c++枚举的末尾添加值
- 在 std::bind 中使用 std::bind :编译错误(隐式强制转换)
- 如何强制 Netbeans 只使用 -ggdb 编译标志而不使用它,同时在 Makefile-Debug.mk 中自动发
- 如何用Cmake强制施用的重新编译
- 在编译时强制执行静态存储
- 如何在交叉编译期间强制链接到未安装的库
- 在C++中,在编译时强制执行函数调用
- 在编译时强制指针指向指针类型
- 很好地要求(不是编译时强制)子类创建者做某些事情