【问题标题】:How to call a constructor from a mixedin mixin template如何从 mixin mixin 模板调用构造函数
【发布时间】:2017-09-20 18:12:21
【问题描述】:

如果我这样做

mixin template T() {
  float y;
  this(float y_){
    y = y_;
  }
}
class C {
  mixin T!() t;
  int x;
  this(int x_, float y_){
    x = x_;
    this(y_);
  }
}
//
C c = new C(5, 7.0f);

这给出了错误 constructor C.this (int x_, float y_) is not callable using argument types (float)。在 C 的构造函数中包含 this(y_); 的行上,这似乎暗示 C 看不到从 T 导入的构造函数。虽然,它应该。

显然t.this(...)T!().this(...) 不起作用。

我能想到的最明显的解决方法是(代理):

template T(...) {
  void constructor(...){...}
  this(Args...)(Args args){ constructor(args); }
}
...
class C {
   mixin T!() t;
   this(...){
     t.constructor(...);
   }
}

但这很糟糕,因为它给 T 带来了更多的知识开销(使用构造函数需要做一些特殊的事情)

有什么方法可以以非奇怪(和非特殊情况)的方式调用 t 的构造函数?另外,这是一个错误吗?如果不是,为什么会这样?

【问题讨论】:

    标签: templates constructor metaprogramming d


    【解决方案1】:

    问题源于这样一个事实,即事物通过 mixin 模板 are not inserted into the aggregate's overload set 混合到一个聚合中。

    对于普通方法,解决方法是在模板 mixin 引入的范围内使用别名,如下所示:

    mixin template T()
    {
        void foo()
        {
        }
    }
    
    class C
    {
        mixin T!() t;
        alias foo = t.foo;
    
        void foo(int _)
        {
            foo();
        }
    }
    

    但是,对于构造函数,类比不起作用,it's a reported bug:

        alias this = t.this;    // Won't compile
        alias __ctor = t.__ctor // Using the hidden __ctor name won't compile, either
    

    如果不需要从外部调用混入构造函数,可以通过内置名称调用:

    mixin template T()
    {
        float y;
        this(float y_)
        {
            y = y_;
        }
    }
    class C
    {
        mixin T!() t;
        int x;
        this(int x_, float y_)
        {
            x = x_;
            t.__ctor(y_); // This
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多