模板可以使用"template this"
,它们允许传递任何类型.
template Test(this ThisType)
{
pragma(msg, ThisType);
}
void main()
{
alias T = Test!int; // Prints "int"
}
这也适用于类模板,结构模板,别名模板,枚举模板
等,但不适用于模板化方法.模板是自由模板还是嵌套在结构或类中都没有关系.
与普通模板类型参数相比有什么优势?
import std.stdio;
class Base {
void test1(T = typeof(this))() {
writeln("test1: ", T.stringof);
}
void test2(this T)() {
writeln("test2: ", T.stringof);
}
}
class Derived: Base {
}
void main()
{
new Base().test1(); //test1: Base
new Base().test2(); //test2: Base
new Derived().test1(); //test1: Base
new Derived().test2(); //test1: Derived
}
是的,我创建了这个问题是因为模板
都允许你使用this T
语法,并且它可以接受任何类型
.它应该只允许用于方法
.