我想将模板中的非限定函数名称带入我的工作/本地范围。例如。:
struct St {
int t = 44;
}
template Inter(T) { // the 'base' template/interface/parameterized-module
alias Self = T;
void myfunc(ref self) {
writeln("Inter: ", Self.stringof, " : ", 11);
}
}
template Inter(T: St) {
/+ ^^^^^ the 'specialization' which is really
the implementation for the template-module for type `St`
+/
alias Self = T;
void myfunc(ref Self self) {
writeln("Inter TWO (St)! : ", Self.stringof, " : ", self.t);
}
}
void main(string[] args){
St s;
/+ SOMETHING HERE +/
/+ s.myfunc(s); +/ // <- I want to be able to do this
}
像
mixin template
这样的东西可以工作,但代价是大量不必要的代码重复(我不会复制任何东西,但编译器必须使用大量相同的代码)。换句话说:是的,即使我可以将
myfunc(self)
带入 main()
的范围,UFCS 在这种情况下甚至可能无法工作。但我的问题是如何将模板范围内的内容公开/不合格地带入另一个范围?或者另一种方式:想象一下,我正在 module
中创建一个嵌套的 mixin template
(我不知道如何做到这一点),使用我想要的类型实例化 mixin,然后 import
将 mymodule_templ!MyType
中的所有内容都放入我的工作范围.请在评论中要求澄清。我的问题在我第一次提出时很少能读懂。谢谢!
最佳答案
您提到了 mixin template
所以也许你试过了,但它没有用......但你所要求的正是 mixin 模板的作用:
import std.stdio;
struct St {
int t = 44;
}
// it needs to be declared as a mixin template
mixin template Inter(T) {
alias Self = T;
void myfunc(ref self) {
writeln("Inter: ", Self.stringof, " : ", 11);
}
}
// the overload is also a mixin template....
mixin template Inter(T: St) {
alias Self = T;
void myfunc(ref Self self) {
writeln("Inter TWO (St)! : ", Self.stringof, " : ", self.t);
}
}
mixin Inter!St; // and this is where you mix it in to the current scope
void main(string[] args){
St s;
s.myfunc(); // boom, this works!
}
您也可以将其混入
main
,但 UFCS 不会在那里工作,因为 ufcs 不考虑本地符号,如果您手动编写函数,它也不会工作。它只查看模块级别。所以
mixin
关键字是 import
你正在寻找的功能......除非我误解了你的问题。
关于module - 将不合格的模板实例化范围中的项目带入本地范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31600184/