www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - template this parameters

reply Trass3r <un known.com> writes:
Why do they exist and why does typeof(this) strip constness?

import std.stdio;
struct S
{
    const void foo(this T)(int i)
    {
	writeln(typeid(T));
    }

    const void bar()
    {
    	writeln(typeid(typeof(this)));
    }
}

void main()
{
    const(S) s;
    (&s).foo(1);
    S s2;
    s2.foo(2);
    immutable(S) s3;
    s3.foo(3);

    s.bar();
    s2.bar();
    s3.bar();
}

yields:
const(templatethis.S)
templatethis.S
immutable(templatethis.S)
templatethis.S
templatethis.S
templatethis.S
Jan 25 2011
next sibling parent "Simen kjaeraas" <simen.kjaras gmail.com> writes:
Trass3r <un known.com> wrote:

 Why do they exist and why does typeof(this) strip constness?
Template this parameters allow for covariant return types, that's about all the use cases I've found for it. It seems like such a great thing, almost doing automatic overriding of methods in subclasses, but that's not what it does. As for typeof(this), that sounds like a bug. -- Simen
Jan 25 2011
prev sibling parent reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Tue, 25 Jan 2011 10:44:23 -0500, Trass3r <un known.com> wrote:

 Why do they exist
It tells you the exact type of this at the call site. For const struct functions, this will tell you what the actual constness of the variable is. For classes, this may give you the derived or base class or interface so you can do more if you want. For example, you could return the derived type for chaining.
 and why does typeof(this) strip constness?
That seems like a bug, but actually, I'd not trust typeid. typeid is actually a runtime-defined TypeInfo class, which you are calling toString on, which is not telling you exactly what the compiler thinks is the type. Try this instead: typeof(this).stringof which is the type the compiler uses. This might still return the wrong type. I seem to remember typeof(this) is handled specially, so you can use it inside static functions. You might try this: auto x = this; writeln(typeof(x).stringof); I would still say it's a bug, it's very surprising that inside a const member function, typeof(this) does not assume the const attribute. -Steve
Jan 25 2011
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Tue, 25 Jan 2011 10:58:18 -0500, Steven Schveighoffer  
<schveiguy yahoo.com> wrote:

 That seems like a bug, but actually, I'd not trust typeid.  typeid is  
 actually a runtime-defined TypeInfo class, which you are calling  
 toString on, which is not telling you exactly what the compiler thinks  
 is the type.
I should clarify, it *could* be the same as what the compiler thinks, but this is not guaranteed. There have been bugs in TypeInfo.toString I believe in the past. -Steve
Jan 25 2011