Mixins with variable number of string arguments in D?

I am working on some D links for an existing C library, and I have a bunch of function definitions and a set of bindings for them. For instance:

// Functions void function(int) funcA; long function() funcB; bool function(bool) funcC; char function(string) funcD; // etc... // Bindings if(!presentInLibrary("func")) return false; if(!bindFunction(funcA, "funcA")) return false; if(!bindFunction(funcB, "funcB")) return false; if(!bindFunction(funcC, "funcC")) return false; if(!bindFunction(funcD, "funcD")) return false; // etc... 

This model is very similar to how Derelict handles OpenGL loading. However, this is similar to over typing. I would really like to express the "binding" part above:

 BINDGROUP("func", "funcA", "funcB", "funcC", "funcD", ...); // Name of function group, then variable list of function names. 

Is this something you can do with mixins?

+4
source share
3 answers

I used this when I was doing dynamic loading, while it does not answer your question, you can adapt it:

 void function() a; int function(int) b; void function(string) c; string bindFunctions(string[] funcs...) { string ret; foreach (func; funcs) { ret ~= func ~ ` = cast(typeof(` ~ func ~ `))lib.getSymbol("` ~ func ~ `");`; } return ret; } mixin(bindFunctions("a", "b", "c")); 

Here bindFunctions("a", "b", "c") returns a string that looks something like this:

 a = cast(typeof(a))lib.getSymbol("a"); b = cast(typeof(b))lib.getSymbol("b"); c = cast(typeof(c))lib.getSymbol("c"); 

Where lib.getSymbol() returns a pointer from dl_open() , etc. Hope this helps.

+5
source

I assume you meant string mixins? You can simply use D vararg syntax straightforwardly:

 string BINDGROUP(string functionGroup, string[] functions...) { // ... } mixin(BINDGROUP("func", "funcA", "funcB", "funcC", "funcD")); 
+4
source

I believe that this is what you are looking for

 template BINDGROUP(string group,T...){ alias BINDGROUP presentInLibrary("func") && BINDGROUPFUNCS!(T); } template BINDGROUPFUNCS(T...){ static if(T.length)alias BINDGROUPFUNCS true; // all is successful else alias BINDGROUPFUNCS bindFunction(mixin(T), T) && BINDGROUPFuncts!(T[1..$]); } 

I am using a recursive template declaration here, you can also do this with foreach loops

+4
source

All Articles