hacky way to get explicit default constructor on struct :P

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Oct 28 23:35:55 UTC 2017


On Saturday, October 28, 2017 16:59:03 LunaticWare via Digitalmars-d wrote:
> Event if there is no default constructor on struct we can still
> make one that work as well as if it were implemented, here is my
> example n__n

This idiom gets suggested from time to time, and I'm sure that it gets used
some, but AFAIK, it's never really caught on much. I think that it's
something that tends to look nice at first for someone looking for a default
constructor but that ultimately, you're better off with other solutions.

Using static opCall allows you to get MyType() to work, but given that it
doesn't get used in a lot of the places a default constructor would need to
be used, it's a lot more limited in usefuleness, and it could be argued that
it would be less error-prone to just create a named factory function for
this to make it more obvious that that's what's going on, given how normally
MyType() and MyType.init would be identical, whereas they wouldn't be in a
type with a static opCall. Certainly, if you're relying on MyType() to be
called as the way that your struct is constructed, then you're just asking
for trouble. This just gives a way to have a no-arg constructor when you're
explicit about it. If you're truly looking for a default constructor, then
you need to rethink how your code works.

Also, this idiom doesn't work if you declare any constructors. In that case,
you're forced to either declare static opCalls for every constructor you
want, or you have to use a factory function for the no-arg constructor
instead of a no-arg static opCall so that you can declare actual
constructors for the other constructors. If you you declare both a static
opCall with no parameters and a constructor, you get an error like this:

q.d(3): Error: struct q.S static opCall is hidden by constructors and can 
never be called
q.d(3):        Please use a factory method instead, or replace all 
constructors with static opCall.

- Jonathan M Davis



More information about the Digitalmars-d mailing list