3
我已经导出了很多样板文件的函数,并试图使用字符串mixin来帮助隐藏混乱并将其加糖。问题是我不知道如何将一个匿名函数传递给字符串mixin。如果可能的话,我想避免把函数写成字符串。从一个字符串调用函数引用mixin
// The function that the anonymous function below ultimately gets passed to.
char* magic(F...)(string function(F) func) { ... }
string genDcode(string name, alias func)() {
return xformat(q{
extern(C) export char* %s(int blah) {
// What would I inject into the string in place of 'func'
// in order to call the 'func' passed into the template?
return magic(func);
}
}, name);
}
// Calls a function to generate code to mix into the global scope.
// The anonymous function must allow abritrary parameters.
mixin(genDcode!("funcName", function(string foo, float bar) {
return "Herpderp";
}));
这当然不是完整的图片,并且大部分样板都被修剪,但它足以显示问题。我曾经想过将函数指针注入为int,并将其重新转换为可调用类型,但不出所料,您只能在运行时获取函数指针。
我试过mixin模板,它可以消除传递函数的问题,但链接器似乎无法找到从这样的mixins生成的导出函数。他们似乎有一些额外的限定符,我不能在DEF文件中使用点。
如果' func'是一个命名和可访问的符号,比如一个常规的命名函数,你可以使用'__traits(identifier,func)'来得到一个可混合的字符串引用,但这不适用于匿名符号。 Mixin模板在这里不起作用,因为mixin模板中的函数名称无论其链接如何都会被破坏。我希望这是固定的,因为mixin模板更清洁,并且感觉不那么黑。无论如何,如果将以下pull请求合并,mixin模板方法在将来可能更加可行:https://github.com/D-Programming-Language/dmd/pull/1085 –
谢谢,我会密切关注那拉请求。我想在使用模板时必须小心避免重复的“损坏”名称,但这对我来说不应该是个问题,因为名称是模板参数之一。 – YotaXP