0
点赞
收藏
分享

微信扫一扫

d的this模板参数

zhyuzh3d 2022-09-17 阅读 139


模板可以使用​​"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​​​语法,并且它可以接受​​任何类型​​​.它应该只允许用于​​方法​​.


举报

相关推荐

0 条评论