What is the best way to program over "abstract" types in D?

mipri mipri at minimaltype.com
Sat Nov 23 23:15:19 UTC 2019


On Saturday, 23 November 2019 at 21:52:40 UTC, Adam D. Ruppe 
wrote:
> On Saturday, 23 November 2019 at 20:22:44 UTC, Ola Fosheim 
> Grøstad wrote:
>> I guess it is possible to use introspection somehow?
>
> Yeah, you have to write a function that checks it with 
> introspection and then static assert on it somewhere.

This is a little bit better. What it's still missing is
a "there's a function with the same signature as this
other function, s/type1/type2/" kinda check.


abstract class Named {
     string name();
}

template isNamed(alias T) {
     import std.traits: hasUDA;

     enum isNamed = hasUDA!(T, Named);
     static if (isNamed) {
         static foreach (f; __traits(getVirtualFunctions, Named, 
"name")) {
             static assert(__traits(compiles, name(T())));
             //static assert(__traits(compiles, f(T())));
         }
     }
}

string greet(T)(T x) if (isNamed!T) {
     return "Hello " ~ x.name;
}
string greet(T)(T x) if (!isNamed!T) {
     return "Hello?";
}

@Named struct World {};
struct Alice {};
@Named struct Bob {};

string name(World x) { return "World"; }
string name(Alice x) { return "Alice"; }
string name(Bob x) { return "Bob"; }

void main() {
     import std.stdio: writeln;

     writeln(greet(World()));
     writeln(greet(Alice()));
     writeln(greet(Bob()));
}



More information about the Digitalmars-d-learn mailing list