下面有两个代码示例。它们都将枚举或枚举类解释为它们的底层类型。当使用多个不同的枚举时,编译后哪一个会更小?
在处理数据序列化项目时,我需要将枚举转换为它们的基础类型、有符号整数和无符号整数。我看到了实现这一目标的两种选择。
在第一种情况下,枚举作为模板参数传递:
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实现。然而,写出这个定义就不那么简单了。
第一个类是为每个枚举类型还是为每个基础类型生成一个实例化?
发布于 2019-06-04 14:27:30
因为my_enum<enumA>和my_enum<enumB>是不同的类型,所以它们得到单独的实例化,即使生成的代码是相同的。
第二个版本将枚举的基础类型作为模板参数传递,这将导致代码减少,因为enumA和enumB都将使用相同的类型作为模板参数,从而生成相同的模板类型。
https://stackoverflow.com/questions/56445872
复制相似问题