1

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
kborkows
  • 158
  • 3
  • 11
  • That can't work. In your example, it looks like there is no problem, but what if someone comes along, pulls out an element of the vector and calls the function pointer (which as per def of the vector *should be* a `IInteractable::*`) on something that is `IInteractable` but not `Unit`? Then you are calling a `Unit` member function on something that isn't a `Unit`, and that's *bad*. This is why the compiler can't let you do what you want. – us2012 Sep 24 '13 at 00:15
  • related: http://stackoverflow.com/questions/4387798/function-pointers-to-member-functions-of-a-parent-class – Nate Kohl Sep 24 '13 at 00:26

1 Answers1

1

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • "even though one might expect such a conversion to make sense." No, I would expect the opposite to make sense -- a pointer to a base class method should be convertible to a pointer to a derived class method. – newacct Sep 24 '13 at 06:33
  • @newacct: It makes sense to me that a pointer to an overridden derived-class function might convert to a pointer to the function it overrides; although you're right that it wouldn't make sense for members in general. But it's irrelevant whether it makes sense to anyone, since it doesn't happen anyway. – Mike Seymour Sep 24 '13 at 09:28