generic toString() in a template class?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Tue Jan 16 12:52:46 PST 2007


%u wrote:
> I wonder how one could write generic toString() method in a template class?
> 
> Suppose, I have a template class S(T), and will pass in as type param: class
> A, struct B, int C:
[snip]

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.
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