我正在爲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