TITLE: binding non-const references to temporaries (Newsgroups: comp.std.c++, 8 Jun 97) [snip] SZONYE: Bradd W. Szonye > Ever since the "no binding temporaries to non-const references" rule, > there have been complaints that some people want to use some objects > that way intentionally. The canonical example is > > ofstream("temp") << foo; > > My own suggestion: allow the use of the 'mutable' keyword on constructor > declarations to indicate that temporaries generated by the constructor > can be bound to non-const (mutable) references. > > class ofstream : public ostream { > public: > mutable ofstream(char const * name, open_mode m = out); // ... > }; POTTER: John Potter suggests instead (in another article): > template > T& lvalue (T const& t) { > return const_cast(t); > } > > Now your problem is solved explicitely > lvalue(ofstream("a_file")) << t; > works for either member or global. And, YOU must say it. SZONYE: I like Mr. Potter's suggestion, because I agree that programmers should explicitly state their intent whenever impossible. On the other hand, I like my suggestion since it lets a library writer define which objects (and which constructors) are appropriate for use as lvalues in the first place. The lvalue template looks more promising for objects with "borderline" reference semantics and the mutable constructor more appropriate for objects (like proxies) which always have lvalue semantics. Discussion of advantages and disadvantages of both? One obvious disadvantage of my idea: it requires a compiler extension. One obvious disadvantage of the lvalue template: it "encourages" naive developers to slap an lvalue() around casts they can't get to work and don't really understand. (I'm not sure whether that's Machiavelli or Murphy at work.)