2

I wrote my own compare function for the third template parameter of std::unorderd_set. My function is

static bool HasSamePosition(const Node& a, const Node& b);

in the class Node. Now I'm trying to use this function in my unordered set,

std::unordered_set<Node, std::hash<Node>, bool(*)(const Node& a, const Node& b)> closedlist(&Node::HasSamePosition);

but it doesn't work. The error ist, that no instance of the constructor is matching the argumentlist. What am I missing?

user3561614
  • 1,024
  • 1
  • 12
  • 20
  • You have to fill in the default arguments for the constructor. Or, even better, wrap the function call in a default constructible function object and pass the type of that as a template parameter. – milleniumbug Mar 17 '16 at 11:03

2 Answers2

4

Well the compiler is right. There is no constructor that allows you to only pass KeyEqual as parameter. You need to use another constructor (see here) or change the type of your function.

E.g. You could use a helper struct that wraps around your HasSamePosition call and override operator()(const Node& a, const Node& b)

struct Node{
    static bool HasSamePosition(const Node& a, const Node& b);
};

struct NodeEqual
{
    bool operator()(const Node& a, const Node& b) { return Node::HasSamePosition(a, b); }
};

int main()
{
    std::unordered_set<Node, std::hash<Node>, NodeEqual> closedlist();
}
Simon Kraemer
  • 5,700
  • 1
  • 19
  • 49
  • Please see my comment on the other answer. – milleniumbug Mar 17 '16 at 11:16
  • @Simon Kraemer how do you suggest to choose the bucket_count constructor parameter, e.g. if I have a maximum of ~400 elements in my unordered_set? – user3561614 Mar 17 '16 at 11:16
  • 1
    @user3561614 I can't decide this w/o having any more information. But since you don't need to pass anything but your `KeyEqual` type/instance: I would recommend to use the `operator()()` method by declaring an extra struct. Either inside your class as in Garf365s answer or as an extra struct as in mine. – Simon Kraemer Mar 17 '16 at 11:20
1

It's easier to use a class:

class Node
{ 
    public:
        class HasSamePosition
        {
            bool operator()(const Node& a, const Node& b)
            { 
                // Put here content of your HasSamePosition function
            }
        };
    ....
};

std::unordered_set<Node, std::hash<Node>, Node::HasSamePosition> closedlist;
Garf365
  • 3,619
  • 5
  • 29
  • 41