best replacement for - cout << "hello D" << endl; ?

Bruce Adams tort.oise74 at do.not.yahoo.spam.me.co.uk
Wed Jul 11 18:36:50 PDT 2007


> 
> Yuck. Operator overloading should not be ambiguous. Each operator should 
> mean one thing and one thing only, or as close as possible. When I see 
> ++ in code, it should indicate that some form of incrementation is going 
> on, not that something is being sent to a stream somewhere. I shouldn't 
> need to know the context in which the operator is being used in order to 
> determine what is going on. There's absolutely no reason to use operator 
> overloads for IO when function calls do the job just fine.
> 
> The use of << and >> for IO in C++ is one of that languages nastiest 
> features. Anything remotely resembling it has no place in D.

Well yes and no. I find myself using the << and >> operators to mean streaming 99% of the time. I use them for shifting much less often.
I thought I read that the argument about operator overloading was one reason D wasn't going to have it a while back. A year or two on and here we are.
I don't want to have to use format strings because of the type safety issues (unless you go down the C# {} route)

stdout << foo << bar << 2 << std::endl;

Is more concise than:

stdout.write(foo);
stdout.write(bar);
stdout.write(2);
stdout.wrteln();

and type safe compared to:

stdout.writefln("%s%s%i", foo,bar,2);

as nothing ensures foo and bar are strings or 2 is a integer
or even that there are enough arguments at compile time.

A compromise like the following
still wouldn't solve the number of arguments problem.

typeinfo[] types = { char[], char[], int };
stdout.write("%%%", types, foo, bar, 2);


lint for C would probably tell me to add a ,0 as a sentinel as well.
With true arrays that shouldn't be a problem for D.

Can we do some clever template foo to make something like the following work?

typeinfo[] types = { char[], char[], int };
object[] args = { foo, bar, 2 }; 
stdout.write!(types, object);

Of course then I'd want a way of constructing lists of objects easily like

foo+bar+2 or cons(foo,bar,2); or use write!(typeinfo[],...)

but crucially one that works at compile time.
Actually why bother with the typeinfo[] at all.

How about:

stdout.write!(...)  -->  foreach (arg;list) { stdout.write(list); }

but with typeof or some such template foo to make it expand at compile time.
I think this would remove the need for << by turning:

cout << foo << bar << 2 << endl;

into:

stdout.write!(foo,bar,2,endl);

Any takers?
Look like I still want an IO manipulator class hierarchy.

Regards,

Bruce.






More information about the Digitalmars-d-learn mailing list