簡體   English   中英

使用 C++17 填充 constexpr 數組

[英]populating a constexpr array using C++17

我正在嘗試通過以下方式使用C++17初始化constexpr數組:

template <size_t N>
struct CStr
{
    static constexpr std::array<int, N> getArr()
    {
        std::array<int, N> a;
        for (auto idx = 0; idx < a.size(); ++idx)
        {
            a[idx] = idx * idx;
        }
        return a;
    }
    static constexpr auto arr { getArr()};
};


int main()
{
    for (const auto &el : CStr<10>::arr)
    {
        std::cout << el << std::endl;
    }
}

但是,這會導致以下關於getArr不是constexpr function 的編譯錯誤。 有人可以幫忙解釋為什么嗎?

<source>: In instantiation of 'constexpr const std::array<int, 10> CStr<10>::arr':
<source>:18:27:   required from 'struct CStr<10>'
<source>:24:35:   required from here
<source>:18:39: error: 'static constexpr std::array<int, N> CStr<N>::getArr() [with long unsigned int N = 10]' called in a constant expression
   18 |     static constexpr auto arr { getArr()};
      |                                 ~~~~~~^~
<source>:9:41: note: 'static constexpr std::array<int, N> CStr<N>::getArr() [with long unsigned int N = 10]' is not usable as a 'constexpr' function because:
    9 |     static constexpr std::array<int, N> getArr()
      |                                         ^~~~~~
<source>:12:9: error: 'goto' is not a constant expression
   12 |         for (auto idx = 0; idx < a.size(); ++idx)
      |         ^~~
Compiler returned: 1   |                                         ^~~~~

這是 C++20 之前 C++ 中的一個限制,請參閱允許在 constexpr 上下文中進行簡單的默認初始化:您必須在constexpr function 中初始化所有變量。 該標准給出了以下示例:

C++17

constexpr int uninit() {
  int a;                  // error: variable is uninitialized
  return a;
}

C++20

constexpr int uninit() {
  struct { int a; } s;
  return s.a;                   // error: uninitialized read of s.a
}

請注意,初始化本身在 C++20 中是可以的。 讀取不確定的值(在“未初始化”對象內)是不行的。


要解決您的問題,請初始化數組或切換到 C++20:

static constexpr std::array<int, N> getArr()
{
    std::array<int, N> a{}; // now initialized!
    for (auto idx = 0; idx < a.size(); ++idx)
    {
        a[idx] = idx * idx;
    }
    return a;
}

暫無
暫無

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

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