UDA usage
Matt Soucy
msoucy at csh.rit.edu
Tue Oct 8 13:59:04 PDT 2013
On 10/04/2013 11:50 PM, Matt Soucy wrote:
> On 10/04/2013 11:04 PM, Adam D. Ruppe wrote:
>> On Saturday, 5 October 2013 at 02:51:21 UTC, Matt Soucy wrote:
>>> * Check to see if a specific attribute exists
>>> * Check to see if an attribute of a specific type exists, something like:
>>
>> The helper functions from my web.d might help:
>>
>> // checks to see if it has one of a type
>> // static if(hasAnnotation!(func, Foo)) { has @Foo }
>> // use if Foo is a simple enum.
>> template hasAnnotation(alias f, Attr) {
>> bool helper() {
>> foreach(attr; __traits(getAttributes, f))
>> static if(is(attr == Attr) || is(typeof(attr) == Attr))
>> return true;
>> return false;
>>
>> }
>> enum bool hasAnnotation = helper;
>> }
>>
>> /// checks to see if it has an annotation with a value e.g. @Something(10)
>> template hasValueAnnotation(alias f, Attr) {
>> bool helper() {
>> foreach(attr; __traits(getAttributes, f))
>> static if(is(typeof(attr) == Attr))
>> return true;
>> return false;
>>
>> }
>> enum bool hasValueAnnotation = helper;
>> }
>>
>> /// gets the thing you checked for above. so getAnnotation!(Func,
>> Something) returns Something(10) (if Something is as struct)
>> template getAnnotation(alias f, Attr) if(hasValueAnnotation!(f, Attr)) {
>> auto helper() {
>> foreach(attr; __traits(getAttributes, f))
>> static if(is(typeof(attr) == Attr))
>> return attr;
>> assert(0);
>> }
>>
>> enum getAnnotation = helper;
>> }
>>
>>
>
> Nice, thank you. These are really helpful!
>
>>> * Create a function that can only be called if the first argument has a
>>> UDA of a specific type
>>
>> Since the UDA is only available at compile time, you can't do that
>> without some kind of template.
>
> Using the above tools I got what I wanted, so I'm satisfied for now.
> Thank you, though!
> -Matt Soucy
>
>
Update on this - unfortunately, I discovered that this doesn't seem to
work for any members, due to requiring a specific "this". I can't quite
figure out why though...
--
Matt Soucy
http://msoucy.me/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20131008/e525afac/attachment.pgp>
More information about the Digitalmars-d-learn
mailing list