How to get constexpr variable as a dimension for declaring an (inline) array?

I assumed the scenario below: start with an empty vector, click on it some int, then use its size to declare the inline array.

  vector<int> vec;      /* default init'ed */

  for(decltype(vec.size()) i = 0; i != 10; ++i){
    vec.push_back(i);
  }


  constexpr size_t sz = vec.size();
  int arr[sz] = {};     /* list init, left out elem are 0 */

The procedure seems to me intuitive (like a beginner). But this fails with the message below:

testconstexpr2.cpp:22:34: error: call to non-constexpr function β€˜std::vector<_Tp, _Alloc>::size_type std::vector<_Tp, _Alloc>::size() const [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
testconstexpr2.cpp:23:13: error: size of array β€˜arr’ is not an integral constant-expression

I would rather stick with the built-in array before getting started, like std :: array or dynamic array alloc.

+4
source share
2 answers

This will not work because it is vec.size()not a function constexpr, and the dimension of the array should be an expression of the compile time constant.

++ 1y/++ 14 ( ) std::dynarray, , , , C + + 1z/++ 17.

,

constexpr size_t sz = 10; /* or any other integral constant expression */
int arr[sz] = {};
+5

constexpr , . constexpr . , constexpr, ( ):

  • LiteralType.
  • .
  • , , ,
  • , ( ), constexpr. constexpr.

++ 7.1.5 constexpr.

std::vector:: size constexpr, . , , , 10:

constexpr size_t sz = 10 ;

, , const, :

const size_t sz = 10;
+2

Source: https://habr.com/ru/post/1547076/


All Articles