C++常量 int 在常量表达式中不可用

C++ const int not usable in constant expression

本文关键字:常量 表达式 int C++      更新时间:2023-10-16

我正在尝试初始化一个数组,我通过外部函数输入其大小。

外部函数计算向量的大小并成对输出它们。

// 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