Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Following error when trying to use std::sort: In template: called object type 'bool' is not a function or function pointer

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading