バイトストリームをプリミティブ型に逆シリアル化する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 */ }
};
これを行うための最良の方法に関するアイデアはありますか?おそらく私が見落としていたより簡単な方法。