d的this模板参数

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

posted @ 2022-09-10 09:20  zjh6  阅读(18)  评论(0)    收藏  举报  来源