Safe copy-paste using mixin

Andrea Fontana via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 31 03:57:21 PDT 2015


On Monday, 31 August 2015 at 10:38:41 UTC, drug wrote:
> On 31.08.2015 13:35, drug wrote:
>> I have code that is being duplicated in several places and I'd 
>> like to
>> use mixins to simplify code maintenance but I failed to do it. 
>> For
>> example 
>> https://github.com/drug007/hdf5-d-examples/blob/tmp/examples/aux.d
>>
>> Lines 80-82, 91-93 and 99-101 are identical, how can I use 
>> mixin here?
>> I failed to do it because mixins demand declarations, not just 
>> code.
>
> Of course I can just trasnfer these lines below, but the 
> question remains.

Just create a function that return a string with those three 
lines and mixin it!

Like:

import std.stdio;

string toMix( string a, string b, string c)
{
	return `string a = "` ~ a ~ `";` ~ `string b = "` ~ b ~ `";` 
`string c = "` ~ c ~ `";`;
}


void main()
{
	
	{
		mixin(toMix("hello", " world", " 1"));
		writeln(a,b,c);
	}
	
	{
		mixin(toMix("hello", " world", " 2"));
		writeln(a,b,c);
	}
}


More information about the Digitalmars-d-learn mailing list