Ali Çehreli wrote:
bearophile wrote:
 > Ali Çehreli:
 >> auto s = S(1, 2);

Doesn't work for structs that have opCall (or maybe an opCall with matching parameters to that use).

 > And by the way, that's the idiomatic way to initialize a struct in D.

Excellent! That's the way I have chosen and have been using in my D tutorial. :)

I had included a warning against the C-style initializers; good to see that they are gone at least for structs with constructors. Since there is also '=void', I think the {} should still default initialize the remaining members (like C and C++).

There's a good chance that C-style struct initializers will be completely removed from the language. It might help to know that struct literals were added at a late stage in language development. Before they were added, there were a few hacky workarounds in the language and compiler; you may encounter them occasionally. Also static opCall was a workaround for not having struct constructors.

One issue remains, which prompted me to open this thread in the first place:

I wanted to experiment with defining opCall for that struct:

struct S
{
    int x;
    int y;

    const int opCall(int p0, int p1)
    {
        return p0 + p1;
    }
}

This does not compile anymore:

    auto s = S(1, 2);
    s(3, 4);          // hoping to call opCall

But compiler error instead:

Error: function expected before (), not s of type int

See, the type of 's' is 'int', meaning that S(1,2) is not a constructor but a call to opCall. (This behavior documented on the struct spec page.)

Here is a consistent deduction of that behavior:

- S(1,2) is always the opCall
- if the programmer doesn't define an opCall, the automatic one is called and the automatic one initializes the members

That is of course my deduction of the current behavior. I don't know what part of that is by design. (?)

Also, I have no clue why we would ever want to use the type name as function call syntax as in S(1,2). Coming from C++, I can understand s(3,4)... :)


Thank you,
Ali

Reply via email to