Access derived type in baseclass static function template

Arafel via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 2 06:38:35 PDT 2017


On 08/02/2017 02:07 PM, Timoses wrote:
> Hey,
> 
> wondering whether it's possible to access the derived type from a 
> function template in the base class or interface.
> 
> this T does not seem to be working, I guess because it's a static 
> function and this does not exists?!
> 
> 

[...]

> 
> Any way I could accomplish this?

Well, it's a clumsy workaround, but the only thing missing seems to be 
the "this T" automatic deduction. I was recently hit by something 
similar: the "this" parameter deduction only works for instance methods.

It was not totally clear if it was a bug or a feature... The 
documentation [1] is however quite clear:

> TemplateThisParameters are used in member function templates to pick up the type of the this reference. 

So, static functions doesn't seem to be covered.

You can, however, make it explicit:

```
B.test!B();
C.test!C();
```

And then even alias it to prevent accidental mismatches:

```
import std.stdio;

interface I
{
     static void test(this T)()
     {
         writeln(T.type.stringof);
     }
}

abstract class A
{
     static void test(this T)()
     {
         writeln(T.type.stringof);
     }
}

class B : A
{
     alias type = uint;
}
class C : I {
     alias type = int;
}

void main() {
     test!B();
     test!C();
}

alias test(T) = T.test!T;
```

[1]: http://dlang.org/spec/template.html#TemplateThisParameter


More information about the Digitalmars-d-learn mailing list