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 @   zjh6  阅读(11)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示