我正在为 avr 芯片编写一个函数,以将字节流反序列化为原始类型。我想以尽可能通用的方式进行操作,并且想知道确定要反序列化的类型的最佳实践是什么。到目前为止,我的想法包括:
选项A:
// Just write a function for each type
double deserialize_double(uint8_t *in) { }
选项 B:
// Use a template, and pass the type in when calling
// Function:
template <typename TYPE>
TYPE deserialize(uint8_t *in) {
union {
TYPE real;
uint8_t base[sizeof(TYPE)];
} u;
for (unsigned int i = 0; i < sizeof(TYPE); i++) {
u.base[i] = in[i];
}
return u.real;
}
// Call:
double value = deserialize<double>(in);
选项 C:
// Similar to B, but you pass in the type as a parameter
// Function:
TYPE deserialize(uint8_t *in, TYPE);
// Call:
double value = deserialize(in, double);
选项 D:
// Use a templated class. My main issue with this is I was hoping
// to re-use the same object for deserializing multiple types.
template <typename TYPE>
class Serializer {
public void serialize(uint8_t *out, TYPE value) { /* code */ }
public TYPE deserialize(uint8_t *int) { /* code */ }
};
关于最好的方法的任何想法?也许我忽略了一个更简单的方法。