Bug 20816 – this template parameter does not work on static method

Status
RESOLVED
Resolution
DUPLICATE
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2020-05-10T01:05:25Z
Last change time
2020-05-10T16:25:42Z
Assigned to
No Owner
Creator
Adam D. Ruppe

Comments

Comment #0 by destructionator — 2020-05-10T01:05:25Z
Consider the following: --- class A { static void one() { pragma(msg, typeof(this)); } static void two(this This)() { } } void main() { A.one(); A.two(); } --- It currently does: $ dmd pow A pow.d(13): Error: template pow.A.two cannot deduce function from argument types !()(), candidates are: pow.d(6): two(this This)() (please note it does the same thing if I use an A instance instead of the type specifically, e.g. `A a; a.one(); a.two();` does the same error.) I vacillated on if this is a bug or if it isn't supposed to work at all. The spec says: "TemplateThisParameters are used in member function templates to pick up the type of the this reference." Now, you're probably thinking "lol silly adam, it is static so there is no `this` reference". But that's why I put the method `one` in there - there is a `this` reference and the compiler knows its type in the normal case. Of course *using* the `this` reference yields the error "this is only defined in non-static member functions", so I grant there is some ambiguity, but the type does clearly exist and the template is really only interested in that static type. Moreover, precisely because template this parameters work strictly via the static type anyway, it needs no dynamic information so there's no theoretical reason I can think of why it shouldn't work. Thus, since the spec is silent on there existing any other exceptions to the rule, I deem that this *should* work per the spec and thus qualifies as an implementation issue, though since there is some ambiguity in the precise meaning of "this reference" in the spec text, I classified it as an enhancement rather than a normal bug per se. Note that if there were `class B : A {}`, then `B.two();` should also work and `is(This == B)` ought to pass inside the `A.two` template implementation.
Comment #1 by pro.mathias.lang — 2020-05-10T14:55:31Z
I had a similar problem recently. Wanted to use `typeof(this)` in a factory method, to return either a `T`, `const(T)`, or `immutable(T)`, but that didn't work out because you're not supposed to use `this` in a static method. But I think it would be a welcome enhancement.
Comment #2 by maxsamukha — 2020-05-10T16:25:42Z
*** This issue has been marked as a duplicate of issue 20277 ***