Как хочется иногда написать:
stream << "(" << x << ", " << y << ")";
А потом зачитать обратно:
stream >> "(" >> x >> ", " >> y >> ")";
А низззя. Изволь прочитать символ, сравнить с '(', не равно — бросить exception. Равно — читай дальше.
Или можно?
class expect
{
public:
explicit expect(const std::string& text) : text_(text) {}
class exception : std::runtime_error
{
public:
explicit exception(const std::string& message) : std::runtime_error(message) {}
};
friend std::istream& operator>>(std::istream& stream, const expect& value)
{
std::istream::sentry s(stream);
if (!s)
{
stream.setstate(std::ios::failbit);
return stream;
}
for (std::string::const_iterator i = value.text_.begin(), e = value.text_.end(); i != e; ++i)
{
char c;
stream.get(c);
if (!stream || c != *i)
{
throw expect::exception("Expected: " + value.text_);
}
}
return stream;
}
private:
const std::string& text_;
};
stream >> expect("(") >> x >> expect(", ") >> y >> expect(")");
Обобщение до произвольных std::basic_stream<Char, Traits> и std::basic_string<Char, Traits, Allocator> оставляется читателю в качестве упражнения