A tutorial on D templates

Jacob Carlborg doob at me.com
Mon Jan 16 12:31:21 PST 2012


On 2012-01-16 12:43, Andrej Mitrovic wrote:
> On 1/15/12, Jacob Carlborg<doob at me.com>  wrote:
>> I'm not completely sure how it works but it
>> looks like that Fields mixin can be replace with the code you have
>> referenced from my Orange library and opDispatch.
>
> You mean your `fieldsOf` template? I'm not really sure how that would
> work, I've tried this:
>
>      This opBinary(string op)(This rhs)
>      {
>          This res;
>          foreach (field; fieldsOf!This)
>          {
>              mixin("res." ~ field ~ " = this." ~ field ~ op ~ " rhs." ~
> field ~ ";");
>          }
>
>          return res;
>      }
>
> But that gives me errors:
> Error: variable __aggr901 cannot be read at compile time
> Error: variable __aggr901 cannot be read at compile time
> Error: variable __key902 cannot be read at compile time
> Error: variable __aggr901 cannot be read at compile time
> Error: variable __aggr901 cannot be read at compile time
>
> Anyway that Fields mixin was something I wrote as a quick example for
> the book. I've also tried using traits(allMembers), but that didn't
> work too good.

This compiles and run as expected for me using dmd 2.057:

http://pastebin.com/fq27831F

But I was thinking if the Fields mixin is necessary at all. Since it's 
possible to get and set the values of structs and objects using tupleof. 
I was thinking it would be possible to use this technique directly in 
Notify. Something like this:

struct Notify (T)
{
     auto opBinary (string op, T) (T rhs)
     {
         T result;
	
         foreach (i, dummy ; T.tupleof)
             mixin("result.tupleof[i] = raw.tupleof[i] " ~ op ~ " 
rhs.tupleof[i];\n");
		
         return result;
     }
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d-announce mailing list