0

I have a private comparator in Level class:

   bool positionCmp(Entity* a, Entity* b);

and when I try to use this in another Level class method:

void Level::drawEntities(std::vector<Entity*> entities)
{
    sort(entities.begin(), entities.end(), positionCmp);
    for (int i = 0; i < entities.size(); ++i) entities[i]->draw();
}

Visual Studio 2019 compiler says: 'Level::positionCmp': non-standard syntax; use '&' to create a pointer to member. If I add the '&', I getting '&': illegal operation on bound member function expression

void Level::drawEntities(std::vector<Entity*> entities)
    {
        sort(entities.begin(), entities.end(), &positionCmp);
        for (int i = 0; i < entities.size(); ++i) entities[i]->draw();
    } 

What should I do?

solacerxt
  • 5
  • 3

2 Answers2

1

You would need something like this:

std::sort(entities.begin(), entities.end(),
  [this](Entity* a, Entity* b) { return positionCmp(a, b); });

This assumes that positionCmp actually refers to some data members of Level, and needs access to a Level instance to do its work. If it does not - if all it needs is two Entity instances passed as parameters - then declare it static, as in

static bool positionCmp(Entity* a, Entity* b);

Then your original version of sort(entities.begin(), entities.end(), positionCmp) would work as is.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
0

Declare the member function static, and use either syntax.

A member function bool positionCmp(Entity* a, Entity* b); in class Level effectively has a third implied parameter with type Level* for the this pointer, even if the definition doesn't actually use this or any members of this. So it can't be called without an argument for "the current object" - either via an level.positionCmp(a, b) or p->positionCmp(a, b) expression, or using the implied this->positionCmp(a, b) within another non-static member function of Level or a derived class.

The static keyword says that the function doesn't need a this object, and so the function can act as an ordinary two-argument function like you expected.

aschepler
  • 70,891
  • 9
  • 107
  • 161