www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - String mixin in templates

reply "Andre" <andre s-e-a-p.de> writes:
Hi,

I have the coding below. The statement mixin(test1("var")); does
exactly what I want. I wonder whether there is maybe a shortcut.
Instead of writing mixin(test1("var")) I want to write s.th. like
test2!("var"). Inside the template the string mixin should happen.
But the coding does not compile, due to the fact that the
variable var is not known to the template.
Is there any other nice shortcut, which has the needed scope?

For my scenario it is necessary that the variable name is handed
over as string and the generated code has access to this scope.

Kind regards
Andre

module main;
import std.stdio;

string test1(string str){
	return "writeln(" ~ str ~ ");";
}

template test2(string str){
	void test2(){
		mixin("writeln(" ~ str ~ ");"); 		
	}
}

void main(){
	string var = "Hello World!";
	
	// Working
	mixin(test1("var"));
	
	// Not working - template does not know var
	test2!("var");
}
Sep 18 2012
next sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
On 9/18/12, Andre <andre s-e-a-p.de> wrote:
 snip

Templates introduce a new scope and in that scope 'var' doesn't exist, what you want are template mixins (note: mixin expressions and template mixins are different things): mixin template test2(string str){ void test2(){ mixin("writeln(" ~ str ~ ");"); } } void main() { mixin test2!"var"; } Note that you don't have to pass the variable by a string, you can use an 'alias' and get rid of that mixin altogether: mixin template test2(alias symb) { void test2() { writeln(symb); } } void main() { string var = "Hello World!"; mixin test2!var; }
Sep 18 2012
prev sibling parent "Andre" <andre s-e-a-p.de> writes:
On Tuesday, 18 September 2012 at 16:13:49 UTC, Andrej Mitrovic
wrote:
 On 9/18/12, Andre <andre s-e-a-p.de> wrote:
 snip

Templates introduce a new scope and in that scope 'var' doesn't exist, what you want are template mixins (note: mixin expressions and template mixins are different things): mixin template test2(string str){ void test2(){ mixin("writeln(" ~ str ~ ");"); } } void main() { mixin test2!"var"; } Note that you don't have to pass the variable by a string, you can use an 'alias' and get rid of that mixin altogether: mixin template test2(alias symb) { void test2() { writeln(symb); } } void main() { string var = "Hello World!"; mixin test2!var; }

What I want to do is to have my own sub language entered as string. The string contains a command, expressions and also variables of the actual scope, which will be read or written to. Therefore I need string mixins. I just wonder wheter there is a possibility not to write at every place "mixin(interpret("..."));" but a nice statement like interpret!("..."); Kind regards Andre
Sep 18 2012