我有一堆结构可以从各种文件中读取,以避免为每个文件定义重复,我考虑过使用以下内容operator>>
: operator<<
#include <fstream>
#pragma pack(push, 1)
template<typename Derived>
struct Base
{
friend std::istream& operator>>(std::istream& stream, Base& base)
{
return stream.read(reinterpret_cast<char*>(&base), sizeof(Derived));
}
friend std::ostream& operator<<(std::ostream& stream, Base const& base)
{
return stream.write(reinterpret_cast<char const*>(&base), sizeof(Derived));
}
};
struct Foo : public Base<Foo>
{
int32_t i;
int8_t j, k, l;
uint16_t m;
};
struct Bar : public Base<Bar>
{
int32_t i;
uint16_t m;
};
#pragma pack(pop)
int main()
{
Foo foo;
Bar bar;
std::ifstream("foobarout", std::ios::binary) >> foo >> bar;
std::ofstream("foobarout", std::ios::binary) << foo << bar;
}
是使用指向明确定义的基类的指针来读取/复制像上面这样的简单 POD 对象(至少在我正在运行的单个平台的范围内,我意识到这不一定是可移植的),还是我在踩在薄冰上?