| |
| Posted by TheFlyingFiddle in reply to TheGag96 | PermalinkReply |
|
TheFlyingFiddle
Posted in reply to TheGag96
| On Tuesday, 14 February 2017 at 06:48:33 UTC, TheGag96 wrote:
> Tonight I stumbled upon Andrei's concept of policy-based design (https://en.wikipedia.org/wiki/Policy-based_design) and tried to implement their example in D with the lack of multiple inheritance in mind.
>
> https://dpaste.dzfl.pl/adc05892344f (btw, any reason why certificate validation on dpaste fails right now?)
>
> The implementation isn't perfect, as I'm not sure how to check members of mixin templates so that you could verify whether print() and message() are actually where they should be. How would you do that? Is there any use for this kind of thing in D, and if so, what would it be? I've hardly dabbled in OOP patterns, but the abstraction seems kinda interesting.
Something like this can be used to check if the mixin has a specific member:
template hasMixinMember(alias mixin_, string member) {
enum hasMixinMember = __traits(compiles, () {
mixin mixin_ mix;
static assert(__traits(hasMember, mix, member));
});
}
struct HelloWorld(alias OutputPolicy, alias LanguagePolicy)
if(hasMixinMember!(OutputPolicy, "print") &&
hasMixinMember!(LanguagePolicy, "message"))
{
mixin OutputPolicy;
mixin LanguagePolicy;
void run() {
print(message());
}
}
Note: This method could fail if you do some compile-time reflection black magic inside the mixins.
Could also do this:
struct HelloWorld(alias OutputPolicy, alias LanguagePolicy)
{
mixin OutputPolicy output;
mixin LanguagePolicy lang;
void run() {
output.print(lang.message());
}
}
If "output" / "lang" does not contain a particular member you will get a compile time error at the usage point (although it's not the best message).
|