Default struct constructor
Ali Çehreli
acehreli at yahoo.com
Thu Jan 28 04:26:04 UTC 2021
On 1/27/21 2:05 PM, Paul wrote:
> Does this mean opCall takes priority over default constructors (or
> struct literals
Assuming static opCall is defined, there are two syntaxes:
S a; // Equals S.init; no constuctor run
S b = S(); // static opCall; no constuctor run
foo(S()); // static opCall
foo(S.init); // S.init
> I have no clue what the difference is, semanthically or
> implementation wise), whilst it does not when arguments are included?
I don't know; let's try. :)
import std.stdio;
struct S {
this(int) {
writeln("ctor");
}
static opCall(int) {
writeln("opCall");
S s;
return s;
}
}
void foo(S) {
}
void main() {
auto a = S(1);
foo(S(2));
}
Both of the calls in main go to this(int); opCall is ignored.
> By the way, doesnt this mean a this(){} syntax could be implemented by
> treating it as syntactic sugar for opCall?
Being able to define a default constructor and then saying we don't have
default constructors would be confusing I think.
> I noticed C++ also has
> non-argument struct constructors, so its a bit curious to me.
Those are called default constructors. D thinks it differently: there
are no default constructors for strtucts. opCall is a strange thing
where the name of the type is callable and it looks like a default
constructor in usage.
Ali
More information about the Digitalmars-d
mailing list