簡體   English   中英

C ++ const 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

正如nwpGianPaolo在對原始問題的評論中所指出的那樣,一種可能的解決方案是避免使用std::array ,而使用允許動態內存分配的容器類型,例如std::vector

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM