一个在不同字节中包含int的类
A class containing int in different Bytes?
我想要一个Record
类,它包含int
,但也可以是int64_t
、int32_t
、int16_t
、int8_t
但是当我想从这个Record
对象中读取数据时,我遇到了问题。
我们上下文中的假设:
我们知道要保存哪个int
我们必须注意getValue()
这样的函数的性能以及这样的类或并集的size。
我会在上下文中尝试3个实现(非常愚蠢)
1.第一个实现:
class Record{
int64_t value;
unsigned int bytes; // number of bytes, in context 1 or 2 or 3 or 4 representing int8_t, int16_t, int32_t, int64_t
int64_t getValue() { return value; }
unsigned int getNumByte() { return bytes; }
}
我会尝试调用getValue()
和getNumByte()
,然后将值强制转换为正确的类型,如if (getNumByte() == 1) auto value = (int8_t getValue())
。
2.第二:使用template
。
template <class T>
class Record{
T value;
T getValue() { return value; }
}
3.第三:使用union
:
union Record {
int64_t int64;
int32_t int32;
int16_t int16;
int8_t int8;
};
我的问题:
关于此上下文,哪个实现更好
当它们都不是那么最优时,你会想出哪种方法?
这个问题的原因:它是char*
的Record
。所以在这种情况下,char* value
和unsigned int length
是有意义的。我想切换到int
的情况,并遇到此问题。
模板是最佳的,因为它总是与底层类型大小相同,并且会被优化掉。一些小改动。
template <class T>
class Record {
T value;
public:
const T& getValue() const { return value; }
}
但是,此解决方案不允许使用具有不同模板参数的Records容器,并且使序列化/反序列化代码更难使用。
此外,如果这个代码对你有用,那么问问自己这个"记录"的用途是什么?我只想使用底层类型本身。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 我该如何循环遍历我的数组(缓冲区——包含一个文本文件),并将其打印成30字节的块
- 如何将包含中文或韩语的字符串转换为十六进制/字节
- 一个在不同字节中包含int的类
- 包含消息长度的两个字节标头上的部分recv()呢?
- 包含载体的构造矢量的字节中的大小,C
- 在仅包含字节而不是指令名称的函数中使用 ASM
- 将包含十六进制值的字符串转换为c中的char字节
- new[] 一个包含构造函数的字节对象数组没有错,对吧?
- setw() 在包含 UTF-8 多字节字符/码位的字符串上输入错误的输出
- 如何构造一个字节数组,其中包含多个数据类型值
- 将char与数据流一起复制到QbyteArray包含一些额外的字节
- 我的类包含 1 个枚举、2 个 int 和一个指针。它没有虚函数,但测量 20 字节。为什么?
- 用C++读取包含空字节的二进制文件
- 如何将字符(字节)中包含的十六进制值转换为整数
- 包含unordered_map的结构的字节大小
- 如何在C++中将包含字节的字符串转换为字节数组
- 为什么dlmalloc分配的块标头包含先前分配的块的4个字节
- 将包含 uint 和 floats 的 4 字节数据转换为 float
- 将包含非ascii字符的字节数组转换为字符串