mercredi 3 avril 2019

Factory with instances of derived classes

I have got kind of a weird use-case. Here's a very simplified version of it.

Let's say I have a class Base and classes DerivedOne and DerivedTwo which are derived from the Base class.

Then, there's a enumeration:

enum DerClasses {Derived1, Derived2};

and a function which would take a enum and return the instance of derived class, depending on the value.

Something like:

inline Base* create_instance(DerClasses enum_class){
    switch(enum_class) {
        case Derived1:
            return new Derived1();
        case Derived2:
            return new Derived2();
    }
}

Obviously this works, but only with the cast to the derived class afterwards.

Derived1 *derived_pointer = dynamic_cast<Derived1*>(pointer);

And I don't want users to make these dynamic casts themselves or even know anything about the classes.

Is that possible to somehow hide these casts and make an API with automatic type deduction, like

auto ptr = create_instance(DerClasses::Derived1);
ptr->derived1_class_only_variable = 123;

Aucun commentaire:

Enregistrer un commentaire