UDA inheritance
Adam D. Ruppe
destructionator at gmail.com
Thu Sep 10 13:35:49 UTC 2020
On Thursday, 10 September 2020 at 13:06:41 UTC, Joseph Rushton
Wakeling wrote:
> `hasUDA!(T, AnotherUDA)`
...do you have to use hasUDA?
The language works with class UDAs, but hasUDA doesn't support it.
If you write your own test function though you can:
``import std.traits;
class BaseUDA {
static BaseUDA opCall(string a) {
return new BaseUDA(a);
}
string a_;
string a() { return a_; }
this(string a) {
this.a_ = a;
}
}
class DerivedUDA : BaseUDA {
static DerivedUDA opCall(string a) { return new
DerivedUDA(a); }
this(string a) { super(a); }
}
@DerivedUDA("test") struct Test {}
BaseUDA hasOurUda(T)() {
BaseUDA found = null;
foreach(uda; __traits(getAttributes, T)) {
static if(is(typeof(uda) : BaseUDA))
found = uda;
}
return found;
}
pragma(msg, hasOurUda!Test);
```
Or, of course, if you are making your own function, you can still
do a plain type == a || b, but the class is fairly natural for
more user extension.
the opCall there is not necessary, it just saves the `new`. This
is equally valid:
@(new DerivedUDA("test")) struct Test {}
You could also use static immutable class instances kinda like
enum instances:
---
import std.traits;
class BaseUDA {
string a_;
string a() const { return a_; }
this(string a) immutable {
this.a_ = a;
}
static immutable A = new immutable BaseUDA("A");
static immutable B = new immutable BaseUDA("B");
}
class DerivedUDA : BaseUDA {
this(string a) immutable { super(a); }
static immutable C = new immutable DerivedUDA("C");
}
// or use B or C or wahtever
@(DerivedUDA.A) struct Test {}
pragma(msg, __traits(getAttributes, Test));
immutable(BaseUDA) hasOurUda(T)() {
// awkward to work around unreachable code warning
BaseUDA found = null;
foreach(uda; __traits(getAttributes, T)) {
static if(is(typeof(uda) : const BaseUDA))
found = cast() uda;
}
return cast(immutable) found;
}
pragma(msg, hasOurUda!Test);
---
so if you are willing to write your own test function there's a
lot of options to consider.
But if you're stuck with Phobos... well, back to the drawing bard.
More information about the Digitalmars-d-learn
mailing list