Awesome. Thanks!

Adam D. Ruppe wrote:

On Tuesday, 21 February 2012 at 14:53:06 UTC, Robert Rouse wrote:

Using a mixin, is it possible to have it define a method based on a
string passed into the mixin?


Yeah, though you'll have to build a string of the method.

Something like this:

string make_method_string(string name) {
string code = "void "; // return type
code ~= name;
code ~= "() {"; // arglist
code ~= q{ // body (q{ } is just another string literal but prettier
for this imo
writeln("hello");
};
code ~= "}";
return code;
}

mixin template make_method(string name) {
mixin(make_method_string(name)); // string mixin runs the above
function at compile time, and then pastes the resulting code in here
to be compiled
}


// and now to use it

struct Test {
mixin make_method("bark");
}


void main() {
Test foo;
foo.bark(); // works!
}





The string mixin and string builder helper function pattern
can do pretty much anything you can think up, though it can
get pretty ugly as it gets bigger just due to being strings.

Reply via email to