Factory pattern in D

Chris via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 1 03:01:16 PDT 2015


What would be the D equivalent of the factory pattern? This 
obviously doesn't work:

struct A {
   int x = 42;
}

struct B {
   int x = 7;
}

auto factory(string type) {
   if (type == "A")
     return A();
   else if (type == "B")
     return B();
   else
     return A();  // default
}

void main()
{
   auto a = factory("A");
}

Error: mismatched function return type inference of B and A

(dmd 2.067.1)


More information about the Digitalmars-d-learn mailing list