我正在为avr芯片编写一个函数,将字节流反序列化为原始类型。我希望尽可能以通用的方式来完成,并想知道确定反序列化类型的最佳实践是什么。想法我到目前为止,包括:在C++函数中传递原始数据类型的最佳做法
选项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 */ }
};
有关最佳方式的任何想法?也许我忽略了一个更简单的方法。
当在这里看到大图时,将这些东西放在类似C++'iostream'的界面中,而不是笨重的C风格函数中是不是更好?相同的'模板'方式将是可能的,但语法最终会更容易理解。 – rubenvb 2011-04-10 09:36:56
@rubenvb - 虽然空间有限,我不想靠近iostream的重复,但我喜欢遵循其功能命名和约定的想法。 – baalexander 2011-04-11 03:49:38
为什么这些'for(unsigned int i = 0; i(in))'。 –
ndim
2011-04-13 23:41:29