Arrays of variants, C++ vs D
Steven Schveighoffer
schveiguy at gmail.com
Thu Jun 17 20:46:19 UTC 2021
On 6/17/21 4:15 PM, H. S. Teoh wrote:
> On Thu, Jun 17, 2021 at 07:44:31PM +0000, JN via Digitalmars-d-learn wrote:
> [...]
>> Foo[int] foos = [
>> 0: Foo("abc"),
>> 1: Foo(5)
>> ];
>> }
>> ```
>>
>> Why does D need the explicit declarations whereas C++ can infer it?
>
> Because D does not support implicit construction. The array literal is
> parsed as-is, meaning string[int] is inferred rather than Foo[int]. So
> the initialization fails because of a type mismatch.
Implicit construction is supported:
struct Foo
{
int x;
this(int y) { x = y; }
}
Foo f = 5; // ok implicit construction
What is happening here though is that the construction is being done as
an AA literal. This works for *some* types, but not all.
e.g.:
Foo[int] f = [5 : 5]; // error
double[int] f = [5 : 5]; // ok
It really should work IMO.
-Steve
More information about the Digitalmars-d-learn
mailing list