C++ Logo

std-proposals

Advanced search

[std-proposals] std::array with enum class for size

From: Jefferson Carpenter <jeffersoncarpenter2_at_[hidden]>
Date: Fri, 22 Jul 2022 11:13:13 -0500
Hello!

Just wondering if it is going to be possible with some of the current
proposals (reflection?) to use an enum class as the size of a std::array.

Currently you have to do things like

enum class MyClass {
   Thing1,
   Thing2,
};
constexpr size_t MyClass_num_elems = 2;

std::array<int, MyClass_num_elems> array;
array[static_cast<size_t>(MyClass::Thing1)] = 1;


What I would like to write instead is:

enum class MyClass {
   Thing1,
   Thing2,
};

std::array<int, MyClass> array;
array[MyClass::Thing1] = 1;


with as little extra ornamentation as possible. The static_cast
everywhere in particular is verbose and leaks the limitations of
std::array's taking a size_t template argument rather than an argument
of any type with an unsigned underlying type.

Some of the code might be reduced with reflection (the
`MyClass_num_elems` defined and maintained in parallel with `MyClass`
might be eliminated) but I'm especially interested in eliminating the
need for a size_t cast by allowing `std::array` to take an enum class
type as its second template parameter. An enum class is (morally
speaking) a type with a fixed and practically small set of options, and
so a pretty natural use case for a std::array. (An enum class is also
natural as the index into a std::tuple or std::variant, but I'm not
discussing that - yet :) ).


If so (if existing proposals are moving in this direction), great - if
not, I might be interested in working to make this possible.

Thanks,
Jefferson

Received on 2022-07-22 16:13:16