Proposal: user defined attributes

F i L witte2008 at gmail.com
Sat Mar 17 21:12:05 PDT 2012


Walter Bright wrote:
> I also do not get why per-instance attributes even exist, as I 
> agree that's what fields are for.

Attributes are per-type (type properties, methods, etc), not 
per-instance, and only accessible (in C#) through type reflection 
(to my knowledge). According to 
http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx 
attribute objects aren't constructed until reflected upon. I 
think attributes in combination with D's templates would be very 
useful:

     @attribute class Cool
     {
         bool isCool;
         this(bool cool)
         {
             isCool = cool;
         }
     }

     class CoolClass(bool cool)
     {
         @CoolType(cool);
         int type;
     }

     void main()
     {
         auto cc = new CoolClass!true();
         if (cc.type at Cool.isCool) { // (new Cool(true)).isCool
             // Do something cool...
         }
     }

Or, if @attributes could be applied to *any* type (enums, 
structs, variables, etc..), we could write this more simply:

     @attribute bool isCool;

     class CoolClass(bool cool)
     {
         @isCool = cool;
         int type;
     }

     void main()
     {
         auto cc = new CoolClass!true();
         if (cc.type at isCool) { // true
             // Do something cool...
         }
     }

and of course, the compiler could make use of attribute metadata 
during codegen. Things like Garbage Collection and memory 
compaction attributes come to mind:

     class MemoryPool
     {
         @GC.DontScan void*[] pool;
         @Int.Fast int index; // replace stdint
     }

Also, aliasing could be possible:

    @Int.Fast alias int intf;
    @Int.Least alias int intl;


More information about the Digitalmars-d mailing list