dimanche 29 mai 2016

C++ - Call function pointers with inherited parameter type

I'm trying to save function-pointers with a base class parameter in a map. Though the functions itself should have derived-class-parameter types.

There's a base class and several derived classes:

class Base
{
    int type;      
};

class DerivedOne : public Base
{   
    DerivedOne() : type(1) { }
};

class DerivedTwo : public Base
{   
    DerivedTwo() : type(2) { }
};

MyClass.h :

typedef void (MyClass::*funcPointer)(const std::shared_ptr<Base>);
std::unordered_map<int, funcPointer> _funcMap;

void receiveInput(const std::vector<std::shared_ptr<Base>> &vector)
void functionOne(std::shared_ptr<DerivedOne> d);
void functionTwo(std::shared_ptr<DerivedTwo> d);

MyClass.cpp :

void MyClass::setupFuncMap()
{
    _funcMap[1]   = (simulationUpdateFuncNew) &MyClass::functionOne;
    _funcMap[2]   = (simulationUpdateFuncNew) &MyClass::functionTwo;
}

void MyClass::receiveInput(const std::vector<std::shared_ptr<Base>> &vector)
{
    for (const auto &data : vector)
    {
        auto func = _funcMap.at(data->type);
        (this->*func)(data);
    }
}

void MyClass::functionOne(std::shared_ptr<DerivedOne> d)
{
    // do work - derived one
}

void MyClass::functionTwo(std::shared_ptr<DerivedTwo> d)
{
    // do work - derived two
}

Is it allowed to call the function pointer with a base class argument like in this example?

In case this is wrong, what is the right way to achieve it?

Aucun commentaire:

Enregistrer un commentaire