Access derived type in baseclass static function template

Timoses via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 2 08:06:51 PDT 2017


Thanks Arafel, the alias workaround might just be a nice way to 
put it.

On Wednesday, 2 August 2017 at 13:51:01 UTC, Steven Schveighoffer 
wrote:
> What you are looking for is virtual static methods, and D 
> doesn't have those. I don't know if there's a way to make it 
> work with existing features.

I'm not looking to overwrite the static method (which would refer 
to virtual, right?).

The solution I had previously was:

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

class B : I {
     alias type = int;

     static void test()
     {
         I.test!type();
     }
}

void main()
{
     B.test();
}

However, this requires to add the base type as in
   I.test!type();
otherwise (only test!type();) it complains about
   Error: template instance test!type test is not a template 
declaration, it is a function

I was hoping there was a way to simply define it in the base 
class/interface without producing redundant code in each derived 
class.

Arafel's solution gets very close!

On Wednesday, 2 August 2017 at 13:51:01 UTC, Steven Schveighoffer 
wrote:
> However, your original code has potential as an enhancement 
> request, as the type is known at compile-time and could 
> certainly be resolved to pass in as the `this` template 
> parameter.

I guess the `this` is really misleading it being a static method.
I suppose 
https://issues.dlang.org/buglist.cgi?bug_severity=enhancement&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&product=D&query_format=report-table&y_axis_field=bug_severity would be the place for an enhancement request?
Possibly related:
https://issues.dlang.org/show_bug.cgi?id=14191


On Wednesday, 2 August 2017 at 14:23:26 UTC, Arafel wrote:
>
>> 
>> What you are looking for is virtual static methods, and D 
>> doesn't have those. I don't know if there's a way to make it 
>> work with existing features.
>> 
>
> Well, there are interesting things to do:
>
> https://dpaste.dzfl.pl/ed826ae21473
>
> I don't know if that's what one would call "virtual static", 
> but I'd say it comes close...

Nifty, but still doesn't allow knowing the derived type B in the 
foo method of A, does it?


More information about the Digitalmars-d-learn mailing list