Is it possible to determine the number of elements of a c++ enum class?

C++C++11CardinalityEnum Class

C++ Problem Overview


Is it possible to determine the cardinality of a c++ enum class:

enum class Example { A, B, C, D, E };

I tried to use sizeof, however, it returns the size of an enum element.

sizeof(Example); // Returns 4 (on my architecture)

Is there a standard way to get the cardinality (5 in my example) ?

C++ Solutions


Solution 1 - C++

Not directly, but you could use the following trick:

enum class Example { A, B, C, D, E, Count };

Then the cardinality is available as static_cast<int>(Example::Count).

Of course, this only works nicely if you let values of the enum be automatically assigned, starting from 0. If that's not the case, you can manually assign the correct cardinality to Count, which is really no different from having to maintain a separate constant anyway:

enum class Example { A = 1, B = 2, C = 4, D = 8, E = 16, Count = 5 };

The one disadvantage is that the compiler will allow you to use Example::Count as an argument for an enum value -- so be careful if you use this! (I personally find this not to be a problem in practice, though.)

Solution 2 - C++

For C++17 you can use magic_enum::enum_count from lib https://github.com/Neargye/magic_enum:

magic_enum::enum_count<Example>() -> 4.

Where is the drawback?

This library uses a compiler-specific hack (based on __PRETTY_FUNCTION__ / __FUNCSIG__), which works on Clang >= 5, MSVC >= 15.3 and GCC >= 9.

We go through the given interval range, and find all the enumerations with a name, this will be their count. Read more about limitations

Many more about this hack in this post https://taylorconor.com/blog/enum-reflection.

Solution 3 - C++

// clang-format off
constexpr auto TEST_START_LINE = __LINE__;
enum class TEST { // Subtract extra lines from TEST_SIZE if an entry takes more than one 
    ONE = 7
  , TWO = 6
  , THREE = 9
};
constexpr auto TEST_SIZE = __LINE__ - TEST_START_LINE - 3;
// clang-format on

This is derived from UglyCoder's answer but improves it in three ways.

  • There are no extra elements in the type_safe enum (BEGIN and SIZE) (Cameron's answer also has this problem.)
    • The compiler will not complain about them being missing from a switch statement (a significant problem)
    • They cannot be passed inadvertently to functions expecting your enum. (not a common problem)
  • It does not require casting for use. (Cameron's answer has this problem too.)
  • The subtraction does not mess with the size of the enum class type.

It retains UglyCoder's advantage over Cameron's answer that enumerators can be assigned arbitrary values.

A problem (shared with UglyCoder but not with Cameron) is that it makes newlines and comments significant ... which is unexpected. So someone could add an entry with whitespace or a comment without adjusting TEST_SIZE's calculation. This means that code formatters can break this. After evg656e's comment, I edited the answer to disable clang-format, but caveat emptor if you use a different formatter.

Solution 4 - C++

// clang-format off
enum class TEST
{
    BEGIN = __LINE__
    , ONE
    , TWO
    , NUMBER = __LINE__ - BEGIN - 1
};
// clang-format on

auto const TEST_SIZE = TEST::NUMBER;

// or this might be better 
constexpr int COUNTER(int val, int )
{
  return val;
}

constexpr int E_START{__COUNTER__};
enum class E
{
    ONE = COUNTER(90, __COUNTER__)  , TWO = COUNTER(1990, __COUNTER__)
};
template<typename T>
constexpr T E_SIZE = __COUNTER__ - E_START - 1;

Solution 5 - C++

It can be solved by a trick with std::initializer_list:

#define TypedEnum(Name, Type, ...)                                \
struct Name {                                                     \
    enum : Type{                                                  \
        __VA_ARGS__                                               \
    };                                                            \
    static inline const size_t count = []{                        \
        static Type __VA_ARGS__; return std::size({__VA_ARGS__}); \
    }();                                                          \
};

Usage:

#define Enum(Name, ...)	TypedEnum(Name, int, _VA_ARGS_)
Enum(FakeEnum, A = 1, B = 0, C)

int main()
{
    std::cout << FakeEnum::A     << std::endl
              << FakeEnun::count << std::endl;
}

Solution 6 - C++

There is one trick based on X()-macros: image, you have the following enum:

enum MyEnum {BOX, RECT};

Reformat it to:

#define MyEnumDef \
    X(BOX), \
    X(RECT)

Then the following code defines enum type:

enum MyEnum
{
#define X(val) val
    MyEnumDef
#undef X
};

And the following code calculates number of enum elements:

template <typename ... T> void null(T...) {}

template <typename ... T>
constexpr size_t countLength(T ... args)
{
    null(args...); //kill warnings
    return sizeof...(args);
}

constexpr size_t enumLength()
{
#define XValue(val) #val
    return countLength(MyEnumDef);
#undef XValue
}

...
std::array<int, enumLength()> some_arr; //enumLength() is compile-time
std::cout << enumLength() << std::endl; //result is: 2
...

Solution 7 - C++

One trick you can try is to add a enum value at the end of your list and use that as the size. In your example

enum class Example { A, B, C, D, E, ExampleCount };

Solution 8 - C++

Reflection TS: static reflection of enums (and other types)

Reflection TS, particularly [reflect.ops.enum]/2 of the latest version of the Reflection TS draft offers the get_enumerators TransformationTrait operation:

> [reflect.ops.enum]/2 > > template struct get_enumerators > > All specializations of get_enumerators<T> shall meet the > TransformationTrait requirements (20.10.1). The nested type named > type designates a meta-object type satisfying > ObjectSequence, containing elements which satisfy Enumerator and > reflect the enumerators of the enumeration type reflected by T.

[reflect.ops.objseq] of the draft covers ObjectSequence operations, where particularly [reflect.ops.objseq]/1 covers the get_size trait for extracting the number of elements for a meta-object satisfying ObjectSequence:

> [reflect.ops.objseq]/1 > > template struct get_size; > > All specializations of get_size<T> shall meet the > UnaryTypeTrait requirements (20.10.1) with a base characteristic of > integral_constant<size_t, N>, where N is the number of elements in > the object sequence.

Thus, in Reflection TS were to be accepted and implemented in its current form, the number of elements of an enum can be computed, at compile time, as follows:

enum class Example { A, B, C, D, E };

using ExampleEnumerators = get_enumerators<Example>::type;

static_assert(get_size<ExampleEnumerators>::value == 5U, "");

where we are likely to see alias templates get_enumerators_v and get_type_v to simplify the reflection further:

enum class Example { A, B, C, D, E };

using ExampleEnumerators = get_enumerators_t<Example>;

static_assert(get_size_v<ExampleEnumerators> == 5U, "");

Status on Reflection TS

As stated by Herb Sutter's Trip report: Summer ISO C++ standards meeting (Rapperswil) from the June 9, 2018 ISO C++ committee summer meeting, Reflection TS has been declared as feature-complete

> Reflection TS is feature-complete: The Reflection TS was declared feature-complete and is being sent out for its main comment ballot over the summer. Note again that the TS’s current template metaprogramming-based syntax is just a placeholder; the feedback being requested is on the core “guts” of the design, and the committee already knows it intends to replace the surface syntax with a simpler programming model that uses ordinary compile-time code and not <>-style metaprogramming.

and was initially planed for C++20, but it's somewhat unclear if Reflection TS will still have a chance to make it into the C++20 release.

Solution 9 - C++

If you make use of boost's preprocessor utilities, you can obtain the count using BOOST_PP_SEQ_SIZE(...).

For example, one could define the CREATE_ENUM macro as follows:

#include <boost/preprocessor.hpp>

#define ENUM_PRIMITIVE_TYPE std::int32_t

#define CREATE_ENUM(EnumType, enumValSeq)                                  \
enum class EnumType : ENUM_PRIMITIVE_TYPE                                  \
{                                                                          \
   BOOST_PP_SEQ_ENUM(enumValSeq)                                           \
};                                                                         \
static constexpr ENUM_PRIMITIVE_TYPE EnumType##Count =                     \
                 BOOST_PP_SEQ_SIZE(enumValSeq);                            \
// END MACRO   

Then, calling the macro:

CREATE_ENUM(Example, (A)(B)(C)(D)(E));

would generate the following code:

enum class Example : std::int32_t 
{
   A, B, C, D, E 
};
static constexpr std::int32_t ExampleCount = 5;

This is only scratching the surface with regards to the boost preprocessor tools. For example, your macro could also define to/from string conversion utilities and ostream operators for your strongly typed enum.

More on boost preprocessor tools here: https://www.boost.org/doc/libs/1_70_0/libs/preprocessor/doc/AppendixA-AnIntroductiontoPreprocessorMetaprogramming.html


As an aside, I happen to strongly agree with @FantasticMrFox that the additional Count enumerated value employed in the accepted answer will create compiler warning headaches galore if using a switch statement. I find the unhandled case compiler warning quite useful for safer code maintenance, so I wouldn't want to undermine it.

Solution 10 - C++

There is another way that doesn’t rely on line counts or templates. The only requirement is sticking the enum values in their own file and making the preprocessor/compiler do the count like so:

my_enum_inc.h

ENUMVAL(BANANA)
ENUMVAL(ORANGE=10)
ENUMVAL(KIWI)
...
#undef ENUMVAL

my_enum.h

typedef enum {
  #define ENUMVAL(TYPE) TYPE,
  #include "my_enum_inc.h"
} Fruits;

#define ENUMVAL(TYPE) +1
const size_t num_fruits =
  #include "my_enum_inc.h"
  ;

This allows you to put comments with the enum values, re-assign values and does not inject an invalid 'count' enum value that needs to be ignored/accounted for in code.

If you don't care about comments you don't need an extra file and can do as someone above mentioned, e.g.:

#define MY_ENUM_LIST \
    ENUMVAL(BANANA) \
    ENUMVAL(ORANGE = 7) \
    ENUMVAL(KIWI)

and replace the #include "my_enum_inc.h" directives with MY_ENUM_LIST but you'll need to #undef ENUMVAL after each use.

Solution 11 - C++

Another kind of "stupid" solution to this is:

enum class Example { A, B, C, D, E };

constexpr int ExampleCount = [] {
  Example e{};
  int count = 0;
  switch (e) {
    case Example::A:
      count++;
    case Example::B:
      count++;
    case Example::C:
      count++;
    case Example::D:
      count++;
    case Example::E:
      count++;
  }

  return count;
}();

By compiling this with -Werror=switch you make sure to get a compiler warning if you omit or duplicate any switch case. It's also constexpr so this is computed at compile time.

But note that even for an enum class the default initialized value is 0 even if the first value of the enum is not 0. So you have to either start on 0 or explicitly use the first value.

Solution 12 - C++

No , you have to write it in the code.

Solution 13 - C++

You can also consider static_cast<int>(Example::E) + 1 which eliminates the extra element.

Solution 14 - C++

This is the solution that worked for me as in 2020, using visual studio 2019

#define Enum(Name, ...)                                                        \
    struct Name {                                                              \
        enum : int {                                                           \
            __VA_ARGS__                                                        \
        };                                                                     \
        private: struct en_size { int __VA_ARGS__; };                          \
        public: static constexpr  size_t count = sizeof(en_size)/sizeof(int);  \
    }   
      

usage:

struct S {

    Enum(TestEnum, a=11, b=22, c=33);

    void Print() {
        std::cout << TestEnum::a << '\n';
        std::cout << TestEnum::b << '\n';
        std::cout << TestEnum::count << '\n';
    }

};


int main()
{        

    S d;
    d.Print();

    return 0
}

output:

11
22
3

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbqueninView Question on Stackoverflow
Solution 1 - C++CameronView Answer on Stackoverflow
Solution 2 - C++NeargyeView Answer on Stackoverflow
Solution 3 - C++EponymousView Answer on Stackoverflow
Solution 4 - C++UglyCoderView Answer on Stackoverflow
Solution 5 - C++ixjxkView Answer on Stackoverflow
Solution 6 - C++Kirill SuetnovView Answer on Stackoverflow
Solution 7 - C++David NehmeView Answer on Stackoverflow
Solution 8 - C++dfribView Answer on Stackoverflow
Solution 9 - C++arr_seaView Answer on Stackoverflow
Solution 10 - C++MetalTurnipView Answer on Stackoverflow
Solution 11 - C++ZitraxView Answer on Stackoverflow
Solution 12 - C++user1944441View Answer on Stackoverflow
Solution 13 - C++Fabio A. CorreaView Answer on Stackoverflow
Solution 14 - C++The OathmanView Answer on Stackoverflow