3

I'm looking for help here.

my class

LevelEditor

has functions like this:

bool SetSingleMast(Game*, GameArea*, GameArea*, vector<IShip*>*);
bool SetDoubleMast(Game*, GameArea*, GameArea*, vector<IShip*>*);
...

In main.cpp I would like to make an array of pointers to LevelEditor object's functions. I'm doing something like this:

bool (*CreateShips[2])(Game*, GameArea*, GameArea*, vector<IShip*>*) = 
{LevelEdit->SetSingleMast, LevelEdit->SetDoubleMast, ...};

But it gives me an error:

error C2440: 'initializing' : cannot convert from 'overloaded-function' to
'bool (__cdecl *)(Game *,GameArea *,GameArea *,std::vector<_Ty> *)'
with
[
    _Ty=IShip *
]
None of the functions with this name in scope match the target type

I don't even know what does it mean. Can somebody help me?

2
  • 5
    A pointer to a function is not the same as a pointer to a member function. I recommend you read about std::function and std::bind Commented May 3, 2013 at 11:56
  • You can't have a pointer to a particular object's function, but to the class' function (method) - LevelEditor::SetSingleMast. Commented May 3, 2013 at 11:56

1 Answer 1

6

You can't use ordinary function pointers to point to non-static member functions; you need pointers-to-members instead.

bool (LevelEditor::*CreateShips[2])(Game*, GameArea*, GameArea*, vector<IShip*>*) =
{&LevelEditor::SetSingleMast, &LevelEditor::SetDoubleMast};

and you need an object or pointer to call them with:

(level_editor->*CreateShips[1])(game, area, area, ships);

although, assuming you can use C++11 (or Boost), you might find it simpler to use std::function to wrap up any kind of callable type:

using namespace std::placeholders;
std::function<bool(Game*, GameArea*, GameArea*, vector<IShip*>*)> CreateShips[2] = {
    std::bind(&LevelEditor::SetSingleMast, level_editor, _1, _2, _3, _4),
    std::bind(&LevelEditor::SetDoubleMast, level_editor, _1, _2, _3, _4)
};

CreateShips[1](game, area, area, ships);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I'll try this and use typedef also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.