Named constructors
Neia Neutuladh
neia at ikeran.org
Wed Jan 9 16:48:31 UTC 2019
On Wed, 09 Jan 2019 08:53:40 +0000, Alex wrote:
> On Wednesday, 9 January 2019 at 07:47:02 UTC, Dru wrote:
>> Another way to distinguish between constructors is needed. Because it
>> is possible to have two different constructors that take the same
>> arguments.
>> Adding dummy arguments that are unused hurts code clarity.
>
> Couldn't this problem be solved by a factory method? I mean,
> either this, or something like this:
> http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-ctor-idiom.html
A constructor can alter const fields, but a factory method can't, so
they're not exactly equivalent. I was hoping you could add a template
parameter to a constructor to give a "name" to it, like:
class Foo
{
const int i;
this(string name: "shift")(int i) { this.i = 1 << i; }
this(string name: "direct")(int i) { this.i = i; }
}
new Foo!"shift"(3);
But that doesn't work; there is no way to explicitly provide template
parameters to a constructor.
More information about the Digitalmars-d
mailing list