C++ istream / ostream equivalent ?

vincent picaud vincent.picaud at laposte.net
Wed Dec 1 09:56:22 PST 2010


Matthias Pleh Wrote:

> Am 01.12.2010 16:51, schrieb vincent picaud:
> > Is there a canonical way to take into account a new type for I/O using the std phobos library ?
> >
> > To be clear I do not know how to translate something like this (in C++)  in D :
> >
> > #include<iostream>
> >
> > class A {};
> >
> > std::ostream&  operator<<(std::ostream&  out,const A&  a)
> > {
> >    out<<  "\nscreen output routine here\n";
> >    return out;
> > }
> >
> > int main()
> > {
> >    A a;
> >    std::cout<<  a;
> > }
> >
> > Do I have to overload some writeln functions ?
> >
> > any help is welcome :)
> 
> I would make it this way:
> 
> module test;
> 
> import std.stdio;
> 
> class A{}
> class B{ string toString() {return "screen output routine here";}}
> 
> int main(string[] args)
> {
>      A a=new A;
>      B b=new B;
>      writeln(a.toString());
>      writeln(b.toString());
>      return 0;
> }
> 
> output:
>  > test.A
>  > screen output routine here
> 
> Base-class of all classes is object with have a default-toString() 
> method, which gives the module.classname.
> So you can overwrite this method.

Thank you for your reply and yes that works :)

Now i m facing with the following problem, what is the trick for input stream ? 

( something like 

std::istream& operator>>(std::istream& in,A& a)
{
  //  A.someData << in; 
  return in;
}

in C++ )

I m thinking of the situation when we want to load some data from a file.

The toString() trick is okay for saving the object... but how to load it back (something like fromString(char[]) would do the job but it does not exist in Object) ?

Anyway thank you, you solved half of my problem :)






More information about the Digitalmars-d-learn mailing list