Question

I know how to create a function that serves as a custom map comparator:

std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(MapComparator);

bool MapComparator(std::string left, std::string right)
{
    return left < right;
}

But I don't know how to do the same with a member function:

bool MyClass::MapComparator(std::string left, std::string right)
{
    return left < right;
}
Was it helpful?

Solution

You have several options:

In C++11 you can use a lambda:

std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(
    [](string lhs, int rhs){ // You may need to put [this] instead of [] to capture the enclosing "this" pointer.
       return MapComparator(lhs, rhs); // Or do the comparison inline
    });

If the function is static, use :: syntax:

class MyClass {
public:
    static bool MyClass::MapComparator(std::string left, std::string right);
};
...
std::map<std::string, std::string, bool (*)(std::string, std::string)> myMap(MyClass::MapComparator);

If the function is non-static, make a static wrapper, member or non-member, and call a member function from it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top