dimanche 26 avril 2020

Cast the static types of n Implementations of an Abstract Class to correspond with their dynamic Type - with at least code as possible

I have a library that works with Actors. An interface for Actor implementation is defined in the abstract class Actor and the actor-library works with Actor*, but in order to use another library I need to implement static functions for each class, and my actor-library naturally thinks every implementation has the static class of Actor, so in order to solve this problem I created the following variant of pointers and a wrapper for an example situation:

ActorImpls = std::variant<
    ActorType1*,
    ActorType2*,
    ActorType3*,
    ActorType4*,
>;

And a cast function that reinterprets the static type to be the same of the dynamic type through checking a dynamic member field:

  ActorImpls staticCorrespond2Dynamic(Actor* cl){
             std::string s = cl->getDynamicName();
                if(s.compare("Dynamic ActorType1")==0){
                    ActorType1* x = reinterpret_cast<ActorType1*>(cl);
                ...

Now I can call static functions for the given ActorImpls with a visitor, but i will always call the function with the same name, it will be ActorType1->staticFunc() or ActorType2->staticFunc(), is there a way to make the wrapper work with less code?

The visitor looks something like this for a static-print-func:

struct VisitPrintStatic{
        VisitPrintStatic() {}
        void operator()(ActorType1* x){x->printStaticName();}
        ...

What else I have tried: implementing with variadic templates, the main problem is that getting the any info on runtime makes is almost impossible to work with. There are the folowing types of functions to consider, they have the same name through all actors:

Actor* ActorX = new ActorTypeX;
ActorX->staticFunc() //where ActorTypeX must be reinterpreted from Actor* to ActorTypeX*
ActorTypeX::staticFunc(ActorTypeX& obj, Args...) //(same as above)

Aucun commentaire:

Enregistrer un commentaire