www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - writef and structs

reply "Ben Hinkle" <ben.hinkle gmail.com> writes:
Is it possible to pass a struct to writef? doFormat doesn't seem to 
recognize them. Try for example
import std.stdio;
struct X{ int x; }
int main() {
  X x;
  writefln(x);
  return 0;
}
one gets an error in formatArg. 
Mar 30 2005
parent reply "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Ben Hinkle" <ben.hinkle gmail.com> wrote in message 
news:d2ec61$17v0$1 digitaldaemon.com...
 Is it possible to pass a struct to writef? doFormat doesn't seem to 
 recognize them. Try for example
 import std.stdio;
 struct X{ int x; }
 int main() {
  X x;
  writefln(x);
  return 0;
 }
 one gets an error in formatArg.
Unsurprisingly. What exactly would you expect it to call to convert a struct to a string? ;) Strangely, classes can be parameters of writefln(). I suspected it was because writefln() was implicitly calling the class's toString(), as that was the result (i.e. if you had class X, and writefln'ed an instance, it'd print "X", which is what X.toString() returns). However, that doesn't seem to be the case with structs. Even if you write a toString() member function, it still throws an exception. I guess you have to call it manually.
Mar 31 2005
parent "Ben Hinkle" <bhinkle mathworks.com> writes:
"Jarrett Billingsley" <kb3ctd2 yahoo.com> wrote in message 
news:d2ho29$1svm$1 digitaldaemon.com...
 "Ben Hinkle" <ben.hinkle gmail.com> wrote in message 
 news:d2ec61$17v0$1 digitaldaemon.com...
 Is it possible to pass a struct to writef? doFormat doesn't seem to 
 recognize them. Try for example
 import std.stdio;
 struct X{ int x; }
 int main() {
  X x;
  writefln(x);
  return 0;
 }
 one gets an error in formatArg.
Unsurprisingly. What exactly would you expect it to call to convert a struct to a string? ;) Strangely, classes can be parameters of writefln(). I suspected it was because writefln() was implicitly calling the class's toString(), as that was the result (i.e. if you had class X, and writefln'ed an instance, it'd print "X", which is what X.toString() returns). However, that doesn't seem to be the case with structs. Even if you write a toString() member function, it still throws an exception. I guess you have to call it manually.
In my case my structs have toString functions so in a perfect world it would automatically call those. Without toString I'd expect it to say the struct name like it does for classes or in the worst case just say "struct". Currently compared to the C++ << mechanism writef comes up short when trying to print structs. I vaguely thought there was a way to have it automatically figure that out but maybe I am mistaken. I was going to suggest TypeInfos get a toString function hook but I haven't thought about it enough to know if that will work.
Mar 31 2005