www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to pass variables to string mixins?

reply Victor Porton <porton narod.ru> writes:
I want to create a string mixin based on a supplementary variable 
(name2 below):

Let we have something like:

mixin template X(string name) {
   immutable string name2 = '_' ~ name;
   mixin("struct " ~ name2 ~ "{ int i; }");
}

But it would create variable name2 inside X, which should not be 
created. How to solve this problem?
Feb 25
next sibling parent Rubn <where is.this> writes:
On Tuesday, 26 February 2019 at 00:07:54 UTC, Victor Porton wrote:
 I want to create a string mixin based on a supplementary 
 variable (name2 below):

 Let we have something like:

 mixin template X(string name) {
   immutable string name2 = '_' ~ name;
   mixin("struct " ~ name2 ~ "{ int i; }");
 }

 But it would create variable name2 inside X, which should not 
 be created. How to solve this problem?
Probably the easiest way is just to move it into another function outside so that it doesn't get mixed in with the mixin template. private string buildStructString(string name2) { return "struct " ~ name2 ~ "{ int i; }" } mixin template X(string name) { mixin(buildStructString("_" ~ name)); }
Feb 25
prev sibling next sibling parent Benjamin Schaaf <ben.schaaf gmail.com> writes:
On Tuesday, 26 February 2019 at 00:07:54 UTC, Victor Porton wrote:
 I want to create a string mixin based on a supplementary 
 variable (name2 below):

 Let we have something like:

 mixin template X(string name) {
   immutable string name2 = '_' ~ name;
   mixin("struct " ~ name2 ~ "{ int i; }");
 }

 But it would create variable name2 inside X, which should not 
 be created. How to solve this problem?
Your best bet is to just not declare anything in a mixin template that you don't want included: mixin template X(string name) { mixin("struct _" ~ name ~ "{ int i; }"); } Or don't use mixin templates: template X(string name) { immutable string name2 = '_' ~ name; enum X = "struct " ~ name2 ~ "{ int i; }"; } mixin(X!("foo"));
Feb 25
prev sibling parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
On Monday, February 25, 2019 5:07:54 PM MST Victor Porton via Digitalmars-d-
learn wrote:
 I want to create a string mixin based on a supplementary variable
 (name2 below):

 Let we have something like:

 mixin template X(string name) {
    immutable string name2 = '_' ~ name;
    mixin("struct " ~ name2 ~ "{ int i; }");
 }

 But it would create variable name2 inside X, which should not be
 created. How to solve this problem?
I'm not sure I quite follow what you mean, but if you're looking for name2 to only exist at compile time rather than creating a variable, then make it an enum. In general, that's what should be done with values that are only intended for use during compile time. - Jonathan M Davis
Feb 25