c++ - 枚举基本类型的模板优化
问题描述
我有下面的两个代码示例。它们都将枚举或枚举类解释为它们的基础类型。当使用多个不同的枚举时,编译后哪个会更小?
在一个数据序列化项目上工作,我需要将枚举转换为它们的底层类型、各种大小的有符号和无符号整数。我看到两个选项来实现这一点。
在第一种情况下,枚举作为模板参数传递:
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 个实现。然而,写出定义并不那么整洁。
第一个类会为每个枚举类型或每个底层类型生成一个实例化吗?
解决方案
由于my_enum<enumA>
和my_enum<enumB>
是不同的类型,因此即使生成的代码相同,它们也会获得单独的实例化。
您的第二个版本将枚举的基础类型作为模板参数传递,这将导致代码更少,因为两者都enumA
将enumB
使用与模板参数相同的类型,生成相同的模板化类型。
推荐阅读
- c# - C# 中有没有办法限制对间接引用的库/DLL 的调用?
- python - 多个scrapy项目到一个scrapyd项目
- mysql - MYSQL 选择字符串包含关键字的位置
- c++ - 我无法预测程序中tellg() 的输出
- r - 向上移动行以填充 NA
- scala - 如何从 S3 读取 JKS 文件并将其解码以在 Scala 中使用?
- excel - 根据在 Frame 中选择的 OptionButton 设置变量
- node.js - ./node_modules/@angular/animations/__ivy_ngcc__/fesm2015/browser.js 中的错误
- wpf - 具有复杂用户控件的 WPF 设计器性能
- notepad++ - Notepad++ 删除 4 位数字,两边有空行