Factory pattern in D
    Rikki Cattermole via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Fri May  1 03:05:42 PDT 2015
    
    
  
On 1/05/2015 10:01 p.m., Chris wrote:
> 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)
Interfaces/classes not structs.
    
    
More information about the Digitalmars-d-learn
mailing list