Search code examples
c++templatesenumsenum-class

Template optimization for enum base type


I have the two code examples below. Both of them interprete an enum or enum class as their underlying type. Which one would be smaller after compilation when using multiple different enums?

Working on a project for data serialization I need to cast enums to their underlying types, signed and unsigned integers of various sizes. I see two options to implement this.

In the first case the enum is passed as a template parameter:

template<class ENUM>
class my_enum
{
  private:
    // Check if the given template parameter is indeed an enum or enum class.
    static_assert(std::is_enum<ENUM>::value, "This class only supports enum and enum classes as template parameter.");

    // Get the underlying type of the enum.
    typedef INT_TYPE = std::underlying_type<ENUM>::type;

  public:
    // Useful code

  private:
    // The actual data
    INT_TYPE data; 
};

Using this would look like:

enum enumA {
 x = 0,
 y,
 z
}

enum enumB {
 a = -10,
 b = -30,
 c =  100
}

my_enum<enumA> A;
my_enum<enumB> B;

The second possibility I see is passing the underlying type directly as template parameter:

template<class INT_TYPE>
class my_enum2
{
  public:
    // Useful code

  private:
    // The actual data
    INT_TYPE data; 
};

This would be used like:

my_enum2<std::underlying_type<enumA>::type> A;
my_enum2<std::underlying_type<enumB>::type> B;

I see the last option only generate 4-6 implementations for singed and unsigned integers of various sizes. Writing out the definition, however, is not so neat.

Would the first class generate an instantiation for every enum type or for every underlying type?


Solution

  • Since my_enum<enumA> and my_enum<enumB> are distinct types, they get separate instantiations, even if the generated code is identical.

    Your second version, where you pass the underlying type of the enum as the template parameter, would result in less code since both enumA and enumB would use the same type as the template parameter, generating the same templated type.