Search code examples
c++functionpointersstdset

std::set as a class member can't use function pointer as key_comp


I want to define a class member std::set with function pointer as key_comp, but compiler report "is not a type".

bool compare(unsigned v1, unsigned v2)
{
    ...
}

std::set<unsigned, decltype(compare)*> GoodSet(compare);

class BadSet{
public:
    ...
    std::set<unsigned, decltype<compare>*> Set2(compare);
};

int main()
{
    BadSet S;
    return 0;
}

GoodSet compiled OK, but GNU C++ report at BadSet: "compare is not a type". My system is windows 10 + WSL 2.0 + ubuntu 20.04.


Solution

  • You can't pass parameters to a member's constructor using parenthesis from inside the parent class declaration, like you are trying to do. You need to either

    • use the member initialization list of the parent class's constructor:
    class BadSet{
    public:
        ...
        std::set<unsigned, decltype<compare>*> Set2;
        BadSet() : Set2(compare) {}
        ...
    };
    
    using myset = std::set<unsigned, decltype<compare>*>;
    
    class BadSet{
    public:
        ...
        myset Set2 = myset{compare};
        or
        myset Set2 = myset(compare);
        ...
    };
    
    • or a brace initializer:
    class BadSet{
    public:
        ...
        std::set<unsigned, decltype<compare>*> Set2{compare};
        ...
    };
    

    See Non-static data members for more details.

    Also see Using custom std::set comparator