c++ - constexpr 变量必须由 const 表达式初始化
问题描述
使用下面的代码,我可以Constexpr variable 'max_digits' must be initialized by a constant expression
运行Apple clang version 12.0.5 (clang-1205.0.22.11)
C++14。
但是,如果我作为一个全局函数#define WORKING_CODE
可以正常工作。base_two_digits
如果我将内容移动base_two_digits
into log_base_10
,我会得到一个错误(这是#undef WORKING_CODE
存在的时候)。
constexpr
如果WORKING_CODE
未定义,为什么不是?
#include <limits>
#include <cstdint>
#include <cmath>
template<typename T>
constexpr T power_of_10(T n)
{
return n < 0 ? 0 : n == 0 ? 1 : (n == 1 ? 10 : 10 * power_of_10(n - 1));
}
#ifdef WORKING_CODE
constexpr std::uint64_t base_two_digits(std::uint64_t value) {
return value ? 8 * sizeof(value) - __builtin_clzll(value) : 0;
};
#endif
template<typename T>
constexpr T log_base_10(T value) {
constexpr const unsigned guess[65] = {
0 ,0 ,0 ,0 , 1 ,1 ,1 , 2 ,2 ,2 ,
3 ,3 ,3 ,3 , 4 ,4 ,4 , 5 ,5 ,5 ,
6 ,6 ,6 ,6 , 7 ,7 ,7 , 8 ,8 ,8 ,
9 ,9 ,9 ,9 , 10,10,10, 11,11,11,
12,12,12,12, 13,13,13, 14,14,14,
15,15,15,15, 16,16,16, 17,17,17,
18,18,18,18, 19
};
#ifdef WORKING_CODE
T digits = guess[base_two_digits(value)];
#else
constexpr auto index = value ? 8 * sizeof(value) - __builtin_clzll(value) : 0;
T digits = guess[index];
#endif
return digits + (value >= power_of_10(digits));
}
class BigInt {
private:
static constexpr const std::uint32_t base = 1000;
static constexpr const std::uint32_t max_digits = log_base_10(base) - 1; // 3;
public:
BigInt() {}
};
int main() {
BigInt p;
return 0;
}
解决方案
让我首先将代码简化为以下示例(请忽略无意义的行为),以说明相同的问题:
template<typename T>
constexpr T log_base_10(T value) {
constexpr auto index = value? 1:0;
return 0;
}
int main() {
constexpr auto foo = log_base_10(42);
return 0;
}
这里的问题是使用不一定是本身的函数参数定义constexpr
变量。如果将在运行时提供,则无法初始化 。index
constexpr
value
index
这个问题不会出现,WORKING_CODE
因为临时索引
T digits = guess[base_two_digits(value)];
不是被迫的constexpr
(但在这种情况下可能是)。另一方面,
constexpr auto index = value ? 8 * sizeof(value) - __builtin_clzll(value) : 0;
是被迫的。
我不能 100% 确定编译器是否可以在这里通过(wrt The Standard),因为函数模板仅针对编译时调用进行实例化。但是因为实例化的函数不能在运行时编译和调用,所以错误应该是有道理的。
解决方案是简单地使用普通的非constexpr
index
.
推荐阅读
- css - 如果无效,CSS 变量默认为 SVG 填充
- google-cloud-platform - 如何修复 terraform 资源“google_cloud_scheduler_job”的“错误 400:'job.pubsub_target.data' (TYPE_BYTES) 的值无效”
- amazon-web-services - 无服务器授权者作为 AWS 用户池
- c# - 从由 Form 1 创建的 Form 2 更新 Form 1 中的控件
- amazon-dynamodb - 从 AWS Dynamodb CLI 查询 GSI
- java - 如何将 2 个 HashMap 合并在一起?
- python - 满足条件时如何求第一行与该行的时间差?
- python - 如何使用 if 条件捕获函数返回值
- ruby - Parse Recursive Collect Deep Nested Category XML children with parents Ids
- ruby - 如何将 Ruby 数组导出到单个 csv 行中?