UDA initialize a user defined type attribute field

Ali Çehreli acehreli at yahoo.com
Tue Feb 18 16:12:53 PST 2014


On 02/18/2014 03:43 PM, Arjan wrote:
> When a user defined type is used as an attribute like this:
> // the attribute
> struct MyAttrib
> {
>      immutable string name;
>      imuttable int sz;
>      immutable string defaultvalue;
> }
>
> // using the attribute
> class Data
> {
>      // field 'id' has attribute MyAttrib with name and sz set to 'fancy
> name'
>      // and 10 resp.
>      @MyAttrib( "fancy name", 10 )
>      long id;
>      ...
> }
>
>
> But how do I only set the MyAttrib.defaultvalue?
>
> class OtherData
> {
>      //@MyAttrib( ??defaultvalue = "null" ?? )
>      //@MyAttrib( string.init, int.init, "null" ) //seems to work?
>      long id;
>      ...
> }
>
> MyAttrib instances may be initialized like this:
>
> auto myattrib = { defaultvalue:"null" };
>
> But this seems not possible when using MyAttrib as attribute.

This problem has nothing to do with UDAs and can be solved similar to 
regular cases, e.g. by using a factory function:

// the attribute
struct MyAttrib
{
     immutable string name;
     immutable int sz;
     immutable string defaultvalue;
}

MyAttrib makeMyAttribWithDefaultValue(string defaultValue)
{
     return MyAttrib(MyAttrib.name.init, MyAttrib.sz.init, defaultValue);
}

// using the attribute
class Data
{
     // field 'id' has attribute MyAttrib with name and sz set to 'fancy 
name'
     // and 10 resp.
     @MyAttrib( "fancy name", 10 )
     long id;

     @makeMyAttribWithDefaultValue("hello")
     int i;
}

void main()
{
     pragma(msg, __traits(getAttributes, Data.id));
     pragma(msg, __traits(getAttributes, Data.i));
}

Ali





More information about the Digitalmars-d-learn mailing list