fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. static int formatId = ios_base::xalloc();
  5.  
  6. ostream & toFoo(ostream & stream) {
  7. stream.iword(formatId) = 1;
  8. return stream;
  9. }
  10. ostream & toBar(ostream & stream) {
  11. stream.iword(formatId) = 2;
  12. return stream;
  13. }
  14.  
  15. struct FooBar {};
  16.  
  17. ostream & operator<<(ostream & stream, FooBar const &) {
  18. switch (stream.iword(formatId)) {
  19. case 1: stream << "foo"; break;
  20. case 2: stream << "bar"; break;
  21. default: stream << "wild foobar";
  22. }
  23. return stream;
  24. }
  25.  
  26. int main() {
  27. FooBar f;
  28. cout << f << toFoo << " " << f << endl;
  29. cout << f << toBar << " " << f << endl;
  30. cout << f << endl;
  31. return 0;
  32. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
wild foobar foo
foo bar
bar