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.
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());
You can use boost::irange:
auto range = boost::irange(0, n + 1);
const vector<int> Foo::numbers(range.begin(), range.end());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With