Search code examples
c++vectorfunction-pointersstd-pair

Passing function pointer as vector<pair<string,X>> X argument


Here is some code:

// Unit.h
typedef void (IInteractable::*fPtr)(Player&);
typedef std::vector<std::pair<std::string, fPtr>> Actions;


// Unit.cpp
Actions Unit::getActions()
{
    Actions a;
    a.push_back(make_pair("Attack", &Unit::attack));
    return a;
}
void attack(Player& p)
{
    cout << "Attack!" << endl;
}

And what i get is error: no matching function for call to ‘std::vector<std::pair<std::basic_string<char>, void (IInteractable::*)(Player&)> >::push_back(std::pair<const char*, void (Unit::*)(Player&)>)’ which seems weird cause Unit inherits from IInteractable. It took me some time to make that problem so "simple" but I have no idea what to do next. Can anyone help?


Solution

  • You need to specify &IInteractable::attack rather than &Unit::attack where an IInteractable member is expected. A pointer to an overridden derived-class function won't convert to the corresponding pointer to the base-class function, even though one might expect such a conversion to make sense.