Factory pattern for classes

lexxn aleksandar.m.nikolov at gmail.com
Sun Aug 9 09:16:46 UTC 2020

I'm trying to get the factory pattern going with classes
class A {}

class B {}

class C {}

auto getClassById(uint id)
     if (id == 0) {
         return cast(A)Object.factory("A");
     } else if(id == 1) {
         return cast(B)Object.factory("B");
     } else {
         return cast(C)Object.factory("C");

I'm getting 2 errors:
main.d(69): Error: Expected return type of main.A, not main.B:
main.d(67):        Return type of main.Ainferred here.

Also is it possible to completely skip the getClassById function 
and if I've and array string classes = ["A", "B"] to just 
cast(classes[0])Object.factory(classes[0]);. I understand that I 
need to cast classes[0].

More information about the Digitalmars-d-learn mailing list