Interactive D?

Matti Niemenmaa see_signature at for.real.address
Tue Feb 26 07:28:51 PST 2008


Oskar Linde wrote:
> Regarding stringof. The following is irritating, given:
> 
> template A(T) { struct A {} }
> template B(T) { struct A {} struct B {} }
> 
> A!(int) a;
> B!(int).B b;
> 
> How do I reliably get the string representation of the type of a and b?
> 
> There are two ways that I know of:
> 
> 1. typeid(typeof(x)).toString
> 2. typeof(x).stringof

Don't forget that .stringof can be overridden in structs/classes. For instance:

import tango.io.Stdout;
class A {
	static char[] stringof = "foo";
}
class B {}

void main() {
	A a;
	B b;

	Stdout(A.stringof).newline;
	Stdout(typeof(a).stringof).newline;
	Stdout((new A).stringof).newline;

	Stdout(B.stringof).newline;
	Stdout(typeof(b).stringof).newline;
	Stdout((new B).stringof).newline;
}

The above prints:

foo
foo
foo
B
B
new B

So .stringof can't really be considered "reliable" per se. Library developers 
should probably always document in big, bold letters: ".stringof should never be 
redefined!!"

I wouldn't be surprised if something like the above were to break much existing 
template code. (Although I don't really know how much .stringof is used in 
practice.)

-- 
E-mail address: matti.niemenmaa+news, domain is iki (DOT) fi



More information about the Digitalmars-d mailing list