generic toString() in a template class?

%u no at where.com
Tue Jan 16 14:29:29 PST 2007


== Quote from Frits van Bommel (fvbommel at REMwOVExCAPSs.nl)'s article
> How about this one:
> -----
>    char[] toString() {
>      return std.string.format("%s", obj);
>    }
> -----
> Works for most types you're likely to want formatted, as long as you
> don't mind how it formats them.

Thank you.  I'd prefer this simple solution; static check on T's type looks too
messy to me.  finally:

===================================
$ cat ts.d
import std.string;

class  A  {char[] toString()  {return "A";}}
struct B  {char[] toString()  {return "B";}}

class S(T) {
  T obj;
  this(T o) {obj = o;}
  char[] toString() {return std.string.format("S!%s", obj);}
}

int main(char[][] args) {
  A a = new A();
  B b;
  int c = 911;

  S!(A)      sa = new S!(   A )( a);
  S!(S!(A)) ssa = new S!(S!(A))(sa);

  S!(B*) sbn = new S!(B*)(null);
  S!(B*)  sb = new S!(B*)(&b);
  S!(B ) ssb = new S!(B )( b);

  S!(int) sc = new S!(int)(c);

  printf("%.*s\n",  sa.toString());
  printf("%.*s\n", ssa.toString());

  printf("%.*s\n", sbn.toString());
  printf("%.*s\n",  sb.toString());
  printf("%.*s\n", ssb.toString());

  printf("%.*s\n", sc.toString());

  return 0;
}

===================================
$ dmd.exe ts.d
g:\project\dmd\bin\..\..\dm\bin\link.exe ts,,,user32+kernel32/noi;

$ ./ts.exe
S!A
S!S!A
S!0000
S!12FF18
S!B
S!911
===================================

> It doesn't support function pointers and delegates, nor will it probably
> like structs without toString() defined, but other than that I think it
> supports everything.
> If you want something a bit more customizable, try something like this:
> (Chris beat me to posting the general idea though)
> -----
> import std.string;	// for .toString and format
> import std.utf;		// for toUTF8
> struct S(T) {
>    T obj;
>    char[] toString() {
>      static if(is(typeof(obj.toString()) : char[]))	// structs with
> toString & objects
>      {
>          return obj ? obj.toString() : "null-obj";
>      }
>      else static if(is(typeof(obj.toUTF8()) : char[]))	// char[],
> wchar[] & dchar[]
>      {
>          return obj.toUTF8();
>      }
>      else static if (is(T : void*))	// pointers
>      {
>          return obj ? format(obj) : "null-ptr";
>      }
>      else static if (is(typeof(std.string.toString(obj)) : char[])) //
> anything supported by std.string.toString
>      {
> 	return std.string.toString(obj);
>      }
>      else
>      {
> 	version(ReportDefaultFormatting) pragma(msg, "Default formatting for "
> ~ T.mangleof);
> 	return format("%s", obj);
>      }
>    }
> }
> -----




More information about the Digitalmars-d mailing list