简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM