Search code examples
c++17static-methodsdecltypestdset

C++ set with customized comparator crashes on insert


STL set can have customized comparator. It can be implemented in several ways, such as define an operator(), use decltype on lambda, etc. I was trying to use a static method of a class and encountered a weird crash. The crash can be demonstrated by the following code

#include <string>
#include <set>

struct Foo {
        static bool Compare(std::string const& s1, std::string const& s2)
        {
                return s1 < s2;
        }
};

std::set<std::string, decltype(&Foo::Compare)> S;

int main()
{
        S.insert("hello");
        S.insert("world");

        return 0;
}

The crash happened on the second insert. Thank you.


Solution

  • You have to pass pointer to compare function to set constructor, otherwise it is null and it is why the code fails.

    std::set<std::string, decltype(&Foo::Compare)> S{&Foo::Compare};
    

    By decltype(&Foo::Compare) you only specify the type of comparator, it has to be provided because its default value is null.