一个在不同字节中包含int的类

A class containing int in different Bytes?

本文关键字:字节 包含 int 的类 一个      更新时间:2023-10-16

我想要一个Record类,它包含int,但也可以是int64_tint32_tint16_tint8_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* valueunsigned int length是有意义的。我想切换到int的情况,并遇到此问题。

模板是最佳的,因为它总是与底层类型大小相同,并且会被优化掉。一些小改动。

template <class T> 
class Record {
T value;
public:
const T& getValue() const { return value; }
}

但是,此解决方案不允许使用具有不同模板参数的Records容器,并且使序列化/反序列化代码更难使用。

此外,如果这个代码对你有用,那么问问自己这个"记录"的用途是什么?我只想使用底层类型本身。