Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ initialize const static vector dynamically

I would like to initalize a static const std::vector in class Foo to {0, 1, 2, 3, ..., n} where n is known at compile time based on the value of Last in the enum below. The goal is for Foo::all to contain all the values of the Fruit enum.

In foo.h:

enum Fruit { Apple, Orange, Banana, ..., Last };

class Foo {
public:
    static const vector<int> all;
};

In foo.cpp:

// initialization of Foo::all goes here.
like image 574
Alan Turing Avatar asked Jun 15 '26 08:06

Alan Turing


2 Answers

As a third option:

namespace {
  std::vector<int> create();
}
const std::vector<int> Foo::all = create();

And create() can do anything it likes, even using push_back() for each element, because the vector it creates isn't const.

Or you could make create() a constexpr function using <index_tuple.h>

#include <redi/index_tuple.h>

namespace {
  template<unsigned... I>
    constexpr std::initializer_list<int>
    create(redi::index_tuple<I...>)
    {
      return { I... };
    }
}

const std::vector<int> Foo::all = create(typename redi::make_index_tuple<Last>::type());
like image 162
Jonathan Wakely Avatar answered Jun 17 '26 23:06

Jonathan Wakely


You can use boost::irange:

auto range = boost::irange(0, n + 1);
const vector<int> Foo::numbers(range.begin(), range.end());
like image 30
Pubby Avatar answered Jun 17 '26 23:06

Pubby