On Wed, Jan 9, 2019 at 5:50 PM Neia Neutuladh via Digitalmars-d <digitalmars-d@puremagic.com> wrote:
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.

import std.stdio;
import std.math;

void main()
{
    auto sa = S.constructorA(3,4);
    auto sb = S.constructorB(3,4);
    writeln(sa);
    writeln(sb);
}


struct S {
public:
   this(string name: "constructorA")(real x, real y)
   {
       this.x = x;
       this.y = y;
   }
    
   this(string name: "constructorB")(real x, real z)
   {
       this.x = x;
       this.z = z;
   } 
   
   static constructorA(Args...)(Args args)
   {
       S s;
       s.__ctor!"constructorA"(args);
       return s;
   }
    
   static constructorB(Args...)(Args args)
   {
       S s;
       s.__ctor!"constructorB"(args);
       return s;
   }
   const real x, y, z;