Home > OS >  Following error when trying to use std::sort: In template: called object type 'bool' is no
Following error when trying to use std::sort: In template: called object type 'bool' is no

Time:10-11

I want to reverse sort a custom container with custom objects, so when sorting this way: (this is part of the .cpp)

bool PictureContainer::isGreater(const Picture& i, const Picture& j) {
    return (i.getId() > j.getId());
}


void PictureContainer::sortRev() {
    sort(picture, picture   tam, isGreater()); 
//< If I try with isGreater, without parenthesis, it says I need to make it static and then it gives same error again.
}

this is part of the .h

class PictureContainer {
private:
    int size;
    Picture *picture;
public:
    PictureContainer();

    PictureContainer(int maxSize);

    bool isGreater (const Picture& i, const Picture& j);

    void sortRev();

CodePudding user response:

It's impossible to use a non-static member function directly as the comparator for std::sort(). There are a few options:

  1. Mark PictureContainer::isGreater as static, and pass PictureContainer::isGreater to std::sort().

  2. Since the implementation of isGreater does not access anything that's only available from the PictureContainer class, we may also make it a free function and pass isGreater to std::sort().

  3. In case the implementation of isGreater has to access some members (or member functions) that's only available within an instance of PictureContainer, we may use a lambda inside the implementation of PictureContainer::isRev as the argument. This is the most flexible solution. For example:

void PictureContainer::sortRev() {
    sort(picture, picture   tam, [this](const Picture& lhs, const Picture& rhs) {
        return this.isGreater(lhs, rhs);
    });
}

CodePudding user response:

isGreater() is a member function of PictureContainer. You cannot pass it to std::sort like that. The easiest way to fix this is to make isGreater() a stand-alone non-member function.

Generally, you can pass pointers to member functions around, but the syntax is convoluted, and you need the object of the class. https://www.tutorialspoint.com/function-pointer-to-member-function-in-cplusplus

  •  Tags:  
  • c
  • Related