class 在不同的字节中包含 int?
A class containing int in different Bytes?
我想提出一个 Record
class,其中包含 int
但它可能是 int64_t
、int32_t
、int16_t
, int8_t
.
但是我遇到了问题,当我想从这个 Record
对象中读取数据时。
我们上下文中的假设:
我们知道要保存哪个int
。
我们要注意performance of getValue()
such function 和 size of such class or union.
我会在上下文中尝试 3 种实现(非常愚蠢)。
1.The 第一次实施:
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.Second: 使用 template
.
template <class T>
class Record{
T value;
T getValue() { return value; }
}
3.Third: 使用 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 容器,并使 serialization/deserialization 代码更难使用。
此外,如果此代码适合您,那么问问自己此 "Record" 的用途是什么?我只会使用底层类型本身。
我想提出一个 Record
class,其中包含 int
但它可能是 int64_t
、int32_t
、int16_t
, int8_t
.
但是我遇到了问题,当我想从这个 Record
对象中读取数据时。
我们上下文中的假设:
我们知道要保存哪个int
。
我们要注意performance of getValue()
such function 和 size of such class or union.
我会在上下文中尝试 3 种实现(非常愚蠢)。
1.The 第一次实施:
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.Second: 使用 template
.
template <class T>
class Record{
T value;
T getValue() { return value; }
}
3.Third: 使用 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 容器,并使 serialization/deserialization 代码更难使用。
此外,如果此代码适合您,那么问问自己此 "Record" 的用途是什么?我只会使用底层类型本身。