c++ - (extract from istream and insert into ostream) operation: is >><T> os; -
i trying overload operator>>
in order extract type t
istream x;
, insert ostream y;
, i.e. x >><t> y;
.
with
template<class t> istream& operator>>(istream& is, ostream& os) { t a; >> a; os << a; return is; }
the prefix notation operator>><string>(x,y);
compiles, postfix notation x >><string> y;
fails compile with
test.cpp:29:9: error: expected expression x >><string> y; ^ test.cpp:29:10: error: unexpected type name 'string': expected expression x >><string> y; ^ 2 errors generated.
and guess >><t>
notation not valid.
just curious if there way postfix version compile? or maybe thoughts whether extract/insert operator makes sense @ all?
short answer, no. operator overloading proceeds according strict grammatical rules, binary operator @
, expression a @ b
considers overloaded functions (a).operator@(b)
, operator@(a, b)
.
the right thing in case make wrapper object:
template <typename t> class pass { std::ostream & os_; public: pass(std::ostream & os) : os_(os) {} friend std::istream & operator>>(std::istream & is, pass & p) { t x; if (is >> x) { p.os_ << x; } return is; } friend std::istream & operator>>(std::istream & is, pass && p) { return >> p; } };
usage:
std::cin >> pass<int>(std::cout);
note we're taking pass<t>
object rvalue reference allow construction.
Comments
Post a Comment