枚举基本类型的模板优化

时间:2019-06-04 14:22:33

标签: c++ templates enums enum-class

我有以下两个代码示例。他们两个都将枚举或枚举类解释为其基础类型。使用多个不同的枚举后,编译后哪个较小?

在进行数据序列化的项目上,我需要将枚举转换为它们的基础类型,即各种大小的有符号和无符号整数。我看到两种方法可以实现这一点。

在第一种情况下,枚举作为模板参数传递:

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; 
};

使用它看起来像:

enum enumA {
 x = 0,
 y,
 z
}

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

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

我看到的第二种可能性是直接将基础类型作为模板参数传递:

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

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

这将被用作:

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

我看到最后一个选项只能为各种大小的单数和无符号整数生成4-6个实现。但是,写出定义并不是那么整齐。

第一类会为每个枚举类型或每个基础类型生成实例化吗?

1 个答案:

答案 0 :(得分:1)

由于my_enum<enumA>my_enum<enumB> distinct 类型,因此即使生成的代码相同,它们也会得到单独的实例化。

第二个版本中,您将枚举的基本类型作为模板参数传递,这会减少代码量,因为enumAenumB都将使用与模板参数相同的类型,从而生成相同的模板类型。

相关问题