C++常量 int 在常量表达式中不可用
C++ const int not usable in constant expression
我正在尝试初始化一个数组,我通过外部函数输入其大小。
外部函数计算向量的大小并成对输出它们。
// The function has been simplified for the sake of the question
std::pair< int, int> calculate_size (
const double in1,
const double in2
)
{
int temp1 = int(in1/in2);
int temp2 = int(in2/in1);
std::pair< int, int> output = make_pair(temp1, temp2);
return output;
}
然后,在其他地方,我提取上述函数的输出以使用 tie 生成数组的大小(我使用 C++11 进行编译):
// Extract sizes
int tempSize1, tempSize2;
tie(tempSize1, tempSize2) = calculate_size (in1, in2);
const int constSize1 = temp1;
const int constSize2 = temp2;
// Initialize vector (compiler error)
std::array<double, constSize1> v1;
std::array<double, constSize2> v2;
编译器给出以下错误:The value of 'constSize1' is not usable in a constant expression
。
但是,我看不出我做错了什么。根据这个C++参考网站,他们带来的例子似乎正是我正在做的事情。
我错过了什么?有没有更好的方法可以做到这一点?
编辑:
一条评论表明constexpr
这就是我需要的。如果我使用它而不更改其余部分,错误消息将移至constexpr
行,但本质上保持不变:
// Modified to use constexpr
int temp1, temp2;
tie(temp1,temp2) = calculate_samples (in1, in2);
constexpr int constSize1 = temp1;
constexpr int constSize2 = temp2;
错误:The value of 'temp1' is not usable in a constant expression
如果您需要array
(而不是vector
),那么将函数标记为constexpr
就可以正常工作。
有关工作代码,请参见下文。这是在 Coliru 上运行的代码:http://coliru.stacked-crooked.com/a/135a906acdb01e08。
#include <iostream>
#include <utility>
#include <array>
constexpr std::pair<int, int> calculate_size (
const double in1, const double in2) {
return std::make_pair(
static_cast<int>(in1 / in2),
static_cast<int>(in2 / in1));
}
int main() {
constexpr auto sizes = calculate_size(4, 2);
std::array<double, sizes.first> v1;
std::array<double, sizes.second> v2;
std::cout << "[Size] v1: " << v1.size() << " - v2: " << v2.size() << "n";
}
其中打印:[Size] v1: 2 - v2: 0
.
正如 nwp 和 GianPaolo 在对原始问题的评论中指出的那样,一种可能的解决方案是避免使用 std::array
,并使用一种允许动态内存分配的容器类型,例如 std::vector
。
相关文章:
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 使用自动推导的 lambda 参数作为常量表达式
- 生成提升::hana::set 的常量表达式问题
- 为什么不能用常量表达式声明数组?
- 不是 lambda 函数中的常量表达式
- 函数调用在常量表达式中必须具有常量值
- 错误:constexpr 变量'struct2Var'必须由常量表达式初始化
- 关于在需要常量表达式的上下文中使用的glvalue常量表达式的问题
- 生成 constexpr 字符串表,不能产生常量表达式
- 整体模板参数。错误:在常量表达式中使用'this'
- 如何在满足常量表达式的同时将整数传递给指针,传递给 std::array<double、integer>?
- 编译器错误:函数调用在常量表达式中必须有一个常量值
- 错误:'new'不能出现在常量表达式中
- 我可以写出小于 -0.5 两个 ulps 的常量表达式双精度吗?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- C++ 使用变量而不是常量表达式初始化数组
- 使用函数参数作为常量表达式的一部分 - gcc vs clang
- 片段着色器中的"错误:在 GLSL 1.30 及更高版本中禁止使用非常量表达式索引的采样器数组"