www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - __traits(getAttributes) with string mixin

reply Jacob Carlborg <doob me.com> writes:
I have some code looking like this. I don't understand why I can use a 
string mixin together with __traits(getAttributes) when it doesn't work 
if I use the template "getAttributes".

template Tuple (T...)
{
     alias T Tuple;
}

struct Foo
{
      (3) int a;
}

template getAttributes (alias s)
{
     alias Tuple!(__traits(getAttributes, s)) getAttributes;
}

void main ()
{
     Foo foo;
     writeln(__traits(getAttributes, mixin("foo.a")));

     // Error: variable foo cannot be read at compile time	
     // writeln(getAttributes!(mixin("foo.a")));

     writeln(getAttributes!(foo.a));
     mixin(`writeln(getAttributes!(foo.a));`);
}

-- 
/Jacob Carlborg
Jan 07 2013
parent Timon Gehr <timon.gehr gmx.ch> writes:
On 01/07/2013 08:40 PM, Jacob Carlborg wrote:
 I have some code looking like this. I don't understand why I can use a
 string mixin together with __traits(getAttributes) when it doesn't work
 if I use the template "getAttributes".

 template Tuple (T...)
 {
      alias T Tuple;
 }

 struct Foo
 {
       (3) int a;
 }

 template getAttributes (alias s)
 {
      alias Tuple!(__traits(getAttributes, s)) getAttributes;
 }

 void main ()
 {
      Foo foo;
      writeln(__traits(getAttributes, mixin("foo.a")));

      // Error: variable foo cannot be read at compile time
      // writeln(getAttributes!(mixin("foo.a")));

      writeln(getAttributes!(foo.a));
      mixin(`writeln(getAttributes!(foo.a));`);
 }

I really do not like how DMD handles alias parameters to instances. void modify(alias a)(){ a = 2; } struct S{ int b = 33; } void main(){ S s; modify!(s.b)(); // error, 'this' missing } The reason it does not work for mixins is presumably that the special casing does not take mixins into account and just rewrites foo.a to Foo.a, but not mixin("foo.a") to Foo.a. I'd prefer if everything behaved like in the mixin case, or alternatively, if the above code snippet worked. (then, modify should be instantiated as a local function of main and a should refer to s.b in modify's function body.)
Jan 10 2013