C++ Logo

std-proposals

Advanced search

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

From: Jefferson Carpenter <jeffersoncarpenter2_at_[hidden]>
Date: Fri, 22 Jul 2022 19:48:34 -0500
On 7/22/2022 5:26 PM, Edward Catmur via Std-Proposals wrote:

> Also, how would you handle non contiguous enumerations?

My initial thought would be that if an enumeration is non-contiguous,
that's more for data marshalling (e.g. putting it into a PoD struct that
can be serialized for I/O). It's not really relevant to the internal
logic of the program. Even if an enumeration is non-contiguous, the
number of elements of the array should equal the number of elements of
the enumeration, and the array should be indexed by the enumeration.
The index operator would have to map them to contiguous values.

The code for this could look something like:


std::vector<int> enumeration_values; // int or underlying type

size_t get_contiguous_index(int enumeration_value) {
   auto contiguous_index = std::find(
     enumeration_values.begin(),
     enumeration_values.end(),
     enumeration_value
   );

   if (contiguous_index == enumeration_values.end()) {
     // throw exception...
   }

   return contiguous_index - enumeration_values.begin();
}

Received on 2022-07-23 00:48:37