c++ - const 好的,但不是 constexpr?
问题描述
使用constexpr
-specified 函数foo_constexpr
,我有如下所示的代码:
const auto x = foo_constexpr(y);
static_assert(x==0);
x
当声明更改为时,在哪些情况下代码可能无法编译constexpr
?(毕竟,x
必须已经是一个常量表达式,以便在 . 中使用static_assert
。)即:
constexpr auto x = foo_constexpr(y);
static_assert(x==0);
解决方案
In general, it can fail to compile when the execution of foo_constexpr
violates a requirement of constant expressions. Remember, a constexpr
function is not a function that is always a constant expression. But rather it is a function that can produce a constant expression for at lease one input! That's it.
So if we were to write this perfectly legal function:
constexpr int foo_constexpr(int y) {
return y < 10 ? 2*y : std::rand();
}
Then we'll get:
constexpr int y = 10;
const auto x1 = foo_constexpr(y); // valid, execution time constant
constexpr auto x2 = foo_constexpr(y); // invalid, calls std::rand
But of course, if x
is already usable in a constant expression (such as a static assertion), changing to constexpr
cannot cause a failure to occur.
推荐阅读
- google-sheets - 如何检测 Google 表格中合并了哪些单元格
- java - 使用 OneToMany 连接维护订单
- numpy - 如何在满足特定条件的情况下创建行索引的 Numpy 矩阵?
- python-3.x - 我想用python解决Image Capthca
- python - 读取 excel 文件后将 StyleFrame obj 转换为 pandas 数据框
- c# - 未处理的异常:Android.Content.Res.Resources+NotFoundException:
发生了 - mysql - 是否可以将 SET 值动态添加到表中?
- python - Pandas- 在各种日期时间范围内分箱分钟数
- php - 我真的可以对致命的解析错误无所事事吗?
- lldb - 调试交互式命令行程序时返回 lldb 提示符