<div dir="ltr"><div dir="ltr"><div dir="ltr">On Wed, Jan 9, 2019 at 5:50 PM Neia Neutuladh via Digitalmars-d <<a href="mailto:digitalmars-d@puremagic.com">digitalmars-d@puremagic.com</a>> wrote:<br></div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">On Wed, 09 Jan 2019 08:53:40 +0000, Alex wrote:<br>
> On Wednesday, 9 January 2019 at 07:47:02 UTC, Dru wrote:<br>
>> Another way to distinguish between constructors is needed. Because it<br>
>> is possible to have two different constructors that take the same<br>
>> arguments.<br>
>> Adding dummy arguments that are unused hurts code clarity.<br>
> <br>
> Couldn't this problem be solved by a factory method? I mean,<br>
> either this, or something like this:<br>
> <a href="http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-ctor-idiom.html" rel="noreferrer" target="_blank">http://www.cs.technion.ac.il/users/yechiel/c++-faq/named-ctor-idiom.html</a><br>
<br>
A constructor can alter const fields, but a factory method can't, so <br>
they're not exactly equivalent. I was hoping you could add a template <br>
parameter to a constructor to give a "name" to it, like:<br>
<br>
class Foo<br>
{<br>
  const int i;<br>
  this(string name: "shift")(int i) { this.i = 1 << i; }<br>
  this(string name: "direct")(int i) { this.i = i; }<br>
}<br>
new Foo!"shift"(3);<br>
<br>
But that doesn't work; there is no way to explicitly provide template <br>
parameters to a constructor.<br></blockquote><div><br></div><div>import std.stdio;</div><div>import std.math;</div><div><br></div><div>void main()</div><div>{</div><div>    auto sa = S.constructorA(3,4);</div><div>    auto sb = S.constructorB(3,4);</div><div>    writeln(sa);</div><div>    writeln(sb);</div><div>}</div><div><br></div><div><br></div><div>struct S {</div><div>public:</div><div>   this(string name: "constructorA")(real x, real y)</div><div>   {</div><div>       this.x = x;</div><div>       this.y = y;</div><div>   }</div><div>    </div><div>   this(string name: "constructorB")(real x, real z)</div><div>   {</div><div>       this.x = x;</div><div>       this.z = z;</div><div>   } </div><div>   </div><div>   static constructorA(Args...)(Args args)</div><div>   {</div><div>       S s;</div><div>       s.__ctor!"constructorA"(args);</div><div>       return s;</div><div>   }</div><div>    </div><div>   static constructorB(Args...)(Args args)</div><div>   {</div><div>       S s;</div><div>       s.__ctor!"constructorB"(args);</div><div>       return s;</div><div>   }</div><div>   const real x, y, z;</div><div>} </div></div></div></div>