d插件模板问题

原文

mixin template helper() {
  mixin("writeln(12);");
}//

struct Foo {
  void opDispatch(string name)() {
    import std.stdio;
    mixin helper!();
    //mixin("writeln(12);");//这有问题
  }
}

void main() {
  Foo.init.opDispatch!"bar"();
}

mixin template不能这样用.它仅接受声明语句,在此.
插件模板仅用来声明新的变量,类型和函数,它不能简单地你那样放call语句.你可:

void helper()
{
    writeln(12);
}

插件模板不能直接带语句,因此需要改两下才能使代码正常工作:
更改插件模板为如下:

mixin template helper() {
    // 在此函数中放语句
    void helper() {
        mixin("writeln(12);");
    }
}

更改实例化位置为:

struct Foo {
  void opDispatch(string name)() {
    import std.stdio;
    mixin helper!();
    helper(); // 在插件模板中,调用函数
  }
}

为什么不直接使用opDispatch()插件模板呢?

mixin template helper() {
  void opDispatch(string name)() {
    import std.stdio;
    writeln(12);
  }
}

struct Foo {
  mixin helper;
  // ...
}

void main() {
  Foo.init.opDispatch!"bar"();
}

有种技术可解决该插件模板限制,我现在找不到.
变通方案不需要更改用户.如下:

mixin template myStatement() {
    auto doIt() {
        import std.stdio : writeln;
        writeln("hi");
        return 0;
    }

    auto ignoreThis = doIt();
}

void main() {
    mixin myStatement!();
    mixin myStatement!();
}

opDispatch根据传入参数生成代码,根据类型插入变量名和函数.我想删除静每一中的双括号(因为在其中声明了些别名,需要这样做,但因为创建了一个外部不能引用这些新变量的域,要用双括号).
在此看到了亚当的帖子.展示了"助手"模板.从此,我去掉了双大括号,去掉了别名,虽然不那么简洁,但很管用.

这并不是插件模板的目的,它们只是复制声明到域中的(因此只支持声明),相反,你需要的是

template helper() {
    const char[] helper = `writeln(12);`;
}

struct Foo {
    void opDispatch(string name)() {
        import std.stdio;
        mixin(helper!());
    }
}

void main() {
    Foo.init.opDispatch!"bar"();
}

在函数中,你可根据整个环境,用普通foreach代替静每一简化事情.
在禁止了普通foreach双大括号函数外中,助手对象很有用.

还可以这样:

template MyContainer(string varS = "")
{
  struct Var
  {
    import std.variant;

    private
    Variant[string] values;
    alias values this;
    @property {
      Variant opDispatch(string name)() const
      {
        return values[name];
      }

      void opDispatch(string name, T)(T val)
      {
        values[name] = val;
      }
    }
  }

  static if(varS.length > 0)
  {
    import std.format;
    mixin(varS.format!"Var %s;");
  } else
    Var data;//这里.
}

void main()
{
  //otherTest("test ok");/*
  mixin MyContainer!"date";
  enum Tarih { AY = 1, YIL = 2023 }

  date.month = cast(ubyte)Tarih.AY;
  date.month.write("/");

  assert(date["month"] != Tarih.AY); //原因
  assert(date["month"].type == typeid(ubyte));

  date.year = cast(short)Tarih.YIL;
  date.year.writeln("土耳其格式");

  assert(date["year"] != Tarih.YIL); //
  assert(date["year"].type == typeid(short));

  writefln("Date: %s/%s", date.year, date.month);//*/
} /* Prints:

  1/2023 in Turkish format
  Date: 2023/1

//*/
import std.stdio;
void otherTest(string str)
{
  mixin MyContainer;
  data.test = str;
  data.test.writeln;
}
posted @   zjh6  阅读(17)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示