d初化含用户定义类型构
原文
我想在B定义中使用A而不是串
struct A {
string s;
this (string s)
{
this.s = s;
}
}
struct B {
A a;
A b;
}
void main ()
{
auto b0 = B (A ("A"), A ("B"));
// 工作,但不想改客户代码
//B b1 = { {"A"}, {"B"} };
// A无显式构造器时工作,但我不想写括号
B b2 = {"A", "B"}; // 工作,但为何?
// auto b3 = B ("A", "B");
//错误:不能隐式转换串到`A`
}
this(string as, string bs) {
this.a = A(as);
this.b = A(bs);
}
}
是的,D禁止一些隐式转换.如上加构造器可工作.
b0,需要this (A, A).b3现在不管用.
{}初化器,风格不一样.我认为应支持,这样复制+粘贴C代码进D,大部分就可工作.
{}的好处是,可用命名初化器.
struct S {
int a;
int b;
}
void main() {
S s = { b : 2, a : 1 };
}
有命名参数时,更好.
struct S {
float a, b;
@disable this(this);
}
enum par : float { a = 1, b = 2 }
S x = { b : par.b, a : par.a };
S y = S(par.a, par.b);
auto s1 = x.a / x.b;
auto s2 = y.a / y.b;
s1.writeln();
s2.writeln();
writeln(s1 + s2);
// x.writeln(y); // 2.087
//上行因@disable,而不管用
"D编译器v".writeln(__VERSION__/1000.0);
问题可化简为:
struct S {
@disable this(this);
}
void foo(S s) {
}
void main() {
auto s = S();
foo(s);
}
错误:因为禁止postblit,不能复制S.
foo按值取,但S禁用复制,
void write(S...)(S args)
{
// ...
foreach (arg; args)
// ...
}
同样,按值.foreach按值迭代参数.同样
命名参数已接受,但未实施.
浙公网安备 33010602011771号