Interactive D?

Jari-Matti Mäkelä jmjmak at utu.fi.invalid
Tue Feb 26 10:21:11 PST 2008


On Tue, 26 Feb 2008, Matti Niemenmaa wrote:

> 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!!"

Oh god. Here's some other results of overriding properties. Again some 
signs of inconsistency can be found:

                                override can be used on
property    can be overridden  runtime  compiletime 
.stringof -         y             y          y
.tupleof  -         y             n          n
.mangleof -         n*            n          y
.init     -         y             y          y
.sizeof   -         n*            n          y

* = override gives error, but still works on compile time

Are there any good reasons for overriding any of those? The override 
doesn't even need to be of the same type.

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

.stringof is pretty much the only way to provide decent compile time 
reflection with D1.



More information about the Digitalmars-d mailing list