如果我做的话
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的构造函数?还有,这是一个错误吗?如果没有,为什么它会这样工作?
答案 0 :(得分:3)
问题源于事物通过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
如果您不需要从外部调用mixed in构造函数,可以通过内置名称调用它:
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
}
}