www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Mixin template, "no identifier for declarator"

reply SimonN <eiderdaus gmail.com> writes:
Hi,

I'd like to generate several very similar class methods with a 
mixin template.
The mixin template shall take alias parameters, so that different 
methods can
bind it to different fields. Reduced problem case:

     class A {
         int myField;

         mixin template fieldSetter(alias whatField)
         {
             whatField = newVal;
         }

         int setMyField(in int newVal)
         {
             mixin fieldSetter!myField;
         }
     }

Compiler error message, DMD64 v2.068.2, line 6 is "whatField = 
newVal;":

     (6): Error: no identifier for declarator whatField
     (6): Error: declaration expected, not '='

I believe I'm following as closely as appropriate what's 
described at
http://dlang.org/template-mixin.html under "Mixins can 
parameterize symbols
using alias parameters".

Why does it error out on whatField, apparently deeming it to be a 
type?

Can I get this done with mixin templates? (I'd like to avoid 
string mixins,
the workaround with them got a little ugly.)

-- Simon
Oct 27 2015
parent reply Andrea Fontana <nospam example.com> writes:
On Tuesday, 27 October 2015 at 07:56:51 UTC, SimonN wrote:
 Hi,

 I'd like to generate several very similar class methods with a 
 mixin template.
 The mixin template shall take alias parameters, so that 
 different methods can
 bind it to different fields. Reduced problem case:
Template mixins can be used only for declaration. Probably what you need is a (non-template) mixin. Check this: http://dlang.org/mixin.html You should generate code you need and then mixin it.
Oct 27 2015
parent SimonN <eiderdaus gmail.com> writes:
On Tuesday, 27 October 2015 at 08:41:24 UTC, Andrea Fontana wrote:
 Template mixins can be used only for declaration.
Thanks for the quick reply! I didn't know that. Now the error message makes sense.
 Probably what you need is a (non-template) mixin.
Yes, it's gonna be a string mixin, or a private method with lots of ref parameters. -- Simon
Oct 27 2015