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上的报告:;compare不是一种类型;。我的系统是windows 10+WSL 2.0+ubuntu 20.04。

不能像您尝试的那样,使用父类声明中的括号将参数传递给成员的构造函数

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

有关详细信息,请参阅非静态数据成员。

另请参阅使用自定义标准::设置比较器

最新更新