首页 > 解决方案 > 枚举基本类型的模板优化

问题描述

我有下面的两个代码示例。它们都将枚举或枚举类解释为它们的基础类型。当使用多个不同的枚举时,编译后哪个会更小?

在一个数据序列化项目上工作,我需要将枚举转换为它们的底层类型、各种大小的有符号和无符号整数。我看到两个选项来实现这一点。

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

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 个实现。然而,写出定义并不那么整洁。

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

标签: c++templatesenumsenum-class

解决方案


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

您的第二个版本将枚举的基础类型作为模板参数传递,这将导致代码更少,因为两者都enumAenumB使用与模板参数相同的类型,生成相同的模板化类型。


推荐阅读