最简单的解决方案是直接使用特殊的缓冲类并重载所需的输出运算符:
struct buffer_class
{
// The data needed...
};
inline buffer_class& operator<<(buffer_class& buffer, const std::string& s)
{
// Code to add the string to the buffer
return buffer;
}
inline buffer_class& operator<<(buffer_class& buffer, const uint8_t ub)
{
// Code to add the value to the buffer
return buffer;
}
inline buffer_class& operator<<(buffer_class& buffer, const int8_t sb)
{
// Code to add the value to the buffer
return buffer;
}
为所需的所有数据添加更多运算符重载。
例如,它可能是这样的:
struct buffer_class
{
std::vector<int8_t> data;
};
inline buffer_class& operator<<(buffer_class& buffer, const std::string& s)
{
for (const auto& ch : s)
buffer.data.push_back(static_cast<unt8_t>(ch));
return buffer;
}
inline buffer_class& operator<<(buffer_class& buffer, const uint8_t ub)
{
buffer.data.push_back(static_cast<int8_t>(ub));
return buffer;
}
inline buffer_class& operator<<(buffer_class& buffer, const int8_t sb)
{
buffer.data.push_back(sb);
return buffer;
}
然后你可以像这样使用它:
buffer_class my_buffer;
buffer << std::string("Hello") << 123:
// The raw data can now be accessed by `my_buffer.data.data()`