I want to create a custom input file stream which automatically strips comments and other garbage data. I came up with the following solution:
class FileReader : public std::ifstream
{
public:
explicit FileReader(const char* fName) { open(fName); }
~FileReader() { if (is_open()) close(); }
template <typename T, bool IsBaseOfSerializable>
struct DoRead
{
void operator()(std::ifstream& ifs, T& data) { ifs >> data; }
};
template <typename T>
struct DoRead<T, true>
{
void operator()(FileReader& reader, T& data) { data.Deserialize(reader); }
};
template <typename T>
friend FileReader& operator>>(FileReader& reader, T& data)
{
reader.SkipCommentsAndGarbage();
DoRead<T, std::is_base_of<ISerializable, T>::value> doread;
doread(reader, data);
return reader;
}
void SkipCommentsAndGarbage() {... }
};
I also have interface ISerializable
containing Serialize/Deserialize
methods. Everything looks fine with me.
But I have read that I should never inherit from std::ifstream
and should create custom std::streambuf
.
Could you please explain why is it bad to inherit from std::ifstream
and how can I create custom std::streambuf
which ignores comments and other data in similar way?