std::set 作为类成员不能使用函数指针作为 key_comp

问题描述

我想用函数指针定义一个类成员 std::set 为 key_comp,但编译器报告“不是类型”。

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 编译正常,但 GNU C++ 在 BadSet 报告:“比较不是类型”。 我的系统是 windows 10 + WSL 2.0 + ubuntu 20.04。

解决方法

您不能像您试图做的那样,从父类声明中使用括号将参数传递给成员的构造函数。你需要

  • 使用父类构造函数的成员初始化列表:
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);
    ...
};
  • 或大括号初始值设定项:
class BadSet{
public:
    ...
    std::set<unsigned,decltype<compare>*> Set2{compare};
    ...
};

有关详细信息,请参阅 Non-static data members

另见Using custom std::set comparator