追加到可空类型数组
Appending to an array of Nullable types
如果我尝试将 Nullable 结构附加到数组,我必须强制转换它,但当我使用索引将它分配给数组时则不需要。这是一个错误还是应该以这种方式工作?
import std.typecons;
struct Foo {
string s;
int i;
}
void main() {
f1();
f2();
f3();
}
void f1() {
auto foos = new Nullable!Foo[](10);
foos[0] = Foo("abc", 10); // OK
}
void f2() {
Nullable!Foo[] foos;
foos ~= Foo("abc", 10); // Error: cannot append type Foo to type Nullable!(Foo)[]
}
void f3() {
Nullable!Foo[] foos;
foos ~= cast(Nullable!Foo)Foo("abc", 10); // OK
}
这是有意为之,但我认为这并不理想。 D 缺少隐式构造(除了在一个非常晦涩的情况下,可变 class 函数,如果你好奇的话)并且你要求的是 Nullable 的隐式构造 - 给定 Foo,你想构建一个 Nullable它的包装器,D 不允许您在没有某种显式操作的情况下这样做,无论是直接构造函数调用还是函数调用,其行为类似于一个*(在某些 user-defined 数组中,重载的 concat 运算符将执行为你构造,但你使用的是 built-in 数组,所以它根本没有超载)。
如果您分配它,它会在 already-constructed 项上调用 Nullable!T.opAssign
;以 http://dpldocs.info/experimental-docs/std.typecons.Nullable.opAssign.html 类型实现的重载函数,它替换了内容。
但是连接意味着需要创建一个新元素,这就符合这个构造规则。
我说它不理想,因为我很希望 D 有这个功能。 C++ 对隐式构造函数有不好的体验,但那是因为所有 C++ 构造函数默认情况下都是隐式的,除非您显式使用 explicit
关键字。 D避免了那个错误,但是把孩子和洗澡水一起扔了出去:(
- 您的转换实际上被编译器重写为构造函数调用:https://dlang.org/spec/expression.html#CastExpression
Casting a value v to a struct S, when value is not a struct of the same type, is equivalent to:
S(v)
如果我尝试将 Nullable 结构附加到数组,我必须强制转换它,但当我使用索引将它分配给数组时则不需要。这是一个错误还是应该以这种方式工作?
import std.typecons;
struct Foo {
string s;
int i;
}
void main() {
f1();
f2();
f3();
}
void f1() {
auto foos = new Nullable!Foo[](10);
foos[0] = Foo("abc", 10); // OK
}
void f2() {
Nullable!Foo[] foos;
foos ~= Foo("abc", 10); // Error: cannot append type Foo to type Nullable!(Foo)[]
}
void f3() {
Nullable!Foo[] foos;
foos ~= cast(Nullable!Foo)Foo("abc", 10); // OK
}
这是有意为之,但我认为这并不理想。 D 缺少隐式构造(除了在一个非常晦涩的情况下,可变 class 函数,如果你好奇的话)并且你要求的是 Nullable 的隐式构造 - 给定 Foo,你想构建一个 Nullable它的包装器,D 不允许您在没有某种显式操作的情况下这样做,无论是直接构造函数调用还是函数调用,其行为类似于一个*(在某些 user-defined 数组中,重载的 concat 运算符将执行为你构造,但你使用的是 built-in 数组,所以它根本没有超载)。
如果您分配它,它会在 already-constructed 项上调用 Nullable!T.opAssign
;以 http://dpldocs.info/experimental-docs/std.typecons.Nullable.opAssign.html 类型实现的重载函数,它替换了内容。
但是连接意味着需要创建一个新元素,这就符合这个构造规则。
我说它不理想,因为我很希望 D 有这个功能。 C++ 对隐式构造函数有不好的体验,但那是因为所有 C++ 构造函数默认情况下都是隐式的,除非您显式使用 explicit
关键字。 D避免了那个错误,但是把孩子和洗澡水一起扔了出去:(
- 您的转换实际上被编译器重写为构造函数调用:https://dlang.org/spec/expression.html#CastExpression
Casting a value v to a struct S, when value is not a struct of the same type, is equivalent to:
S(v)