User defined attributes use

simendsjo simendsjo at gmail.com
Fri Sep 20 07:12:57 PDT 2013


On Friday, 20 September 2013 at 07:57:43 UTC, Jacob Carlborg 
wrote:
> On 2013-09-20 08:59, ilya-stromberg wrote:
>
>> Can I explicitly specify when I can use attribute? Something 
>> like
>> this:
>>
>> @attribute("field")
>> struct matches(string mustMatch)
>> {
>> }
>>
>> string wrongAttribute
>> {
>> }
>>
>> class Foo
>> {
>>     @matches("[0-9]+")
>>     string someNumber; //OK, it's a field
>> }
>>
>> @matches("[0-9]+") //Error, it's a class, not a field
>> class Bar
>> {
>> }
>>
>> @wrongAttribute //Error, this attribute doesn't exist
>> class C
>> {
>> }
>
> Unfortunately you can't. I tag all my structs which are 
> supposed to be used as UDA's with a @attribute UDA.
>
> struct attribute {}
>
> @attribute struct matches(string mustMatch) {}
>
> Then I have some wrappers around __traits(getAttributes) that 
> will, by default, only return UDA's that them self have the 
> @attribute UDA attached to them.
>
> https://github.com/jacob-carlborg/orange/blob/master/orange/core/Attribute.d

You could of course fix this in a library too.

enum AttributeUsage {
   struct_ = 1 << 0,
   class_ = 1 << 1,
   //etc
}

struct attribute { AttributeUsage usage; }

Then the library could give a compile-time error if you tries to 
use it where it's not meant to be.


More information about the Digitalmars-d-learn mailing list