Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Wherever you go, there you are

Name: Anonymous 2010-09-15 21:57

Q: Can I use C++'s syntax for ostreams: cout << x << y ... ?

You can. If you don't like writing ``print x, y'' then you can try this:
import sys

class ostream:
    def __init__(self, file):
        self.file = file
       
    def __lshift__(self, obj):
        self.file.write(str(obj));
        return self

cout = ostream(sys.stdout)
cerr = ostream(sys.stderr)
nl = '\n'

cout << x << " " << y << nl


This gives you a different syntax, but it doesn't give you a new convention for printing--it just packages up the str convention that already exists in Python. This is similar to the toString() convention in Java. C++ has a very different convention: instead of a canonical way to convert an object to a string, there is a canonical way to print an object to a stream (well, semi-canonical---a lot of C++ code still uses printf). The stream approach is more complicated, but it does have the advantage that if you need to print a really huge object you needn't create a really huge temporary string to do it.

Name: Anonymous 2010-09-17 0:50

>>15
Since it is Java, it should be handled through a method in the String class; usage of the + symbol is a special case and gives the naive programmer a false impression of mutability when all it is really doing is allowing shortcuts at the cost of GC work.  Moreover, Java already contains two other intentionally mutable string-likes named StringBuffer and StringBuilder that do not create a new object whenever you do something to the text contents.

You know what I am proposing?  Java can return interface types as well as classes.  Because both mutable and immutable string objects both use the same interface, I propose Java replaces most String returns with CharSequence returns.  That way, we can decide whether or not the output is worth changing later.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List