枚举基类型的模板优化
Template optimization for enum base type
我有下面的两个代码示例。他们都将枚举或枚举 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 个实现。然而,写出定义并不是那么简洁。
第一个 class 会为每个枚举类型或每个基础类型生成一个实例吗?
由于 my_enum<enumA>
和 my_enum<enumB>
是 不同的 类型,即使生成的代码相同,它们也会得到单独的实例化。
你的第二个版本,你将枚举的基础类型作为模板参数传递,将导致更少的代码,因为 enumA
和 enumB
将使用相同的类型作为模板参数, 生成相同的模板化类型。
我有下面的两个代码示例。他们都将枚举或枚举 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 个实现。然而,写出定义并不是那么简洁。
第一个 class 会为每个枚举类型或每个基础类型生成一个实例吗?
由于 my_enum<enumA>
和 my_enum<enumB>
是 不同的 类型,即使生成的代码相同,它们也会得到单独的实例化。
你的第二个版本,你将枚举的基础类型作为模板参数传递,将导致更少的代码,因为 enumA
和 enumB
将使用相同的类型作为模板参数, 生成相同的模板化类型。