std::set 作为类成员不能使用函数指针作为 key_comp
Posted
技术标签:
【中文标题】std::set 作为类成员不能使用函数指针作为 key_comp【英文标题】:std::set as a class member can't use function pointer as key_comp 【发布时间】:2021-03-15 03:35:48 【问题描述】:我想定义一个类成员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。
【问题讨论】:
对类成员初始化器使用大括号:std::set<unsigned, decltype<compare>*> Set2compare;
谢谢! Set2compare 有效。但是为什么类中的 std::set 定义需要不同的语法呢?
@wuyabiao -- 仔细看看你的尝试。如何构造一个需要使用括号(不是大括号)参数的类成员对象?您将需要使用成员初始化列表。另请注意,如果您有struct B B(int) ;
并尝试将B
作为BadSet
的类成员,您也会遇到同样的问题。所以问题与std::set
无关。
【参考方案1】:
您不能像您尝试做的那样,在父类声明中使用括号将参数传递给成员的构造函数。你需要
使用父类构造函数的成员初始化列表:class BadSet
public:
...
std::set<unsigned, decltype<compare>*> Set2;
BadSet() : Set2(compare)
...
;
通过等式初始化器使用list-initialization:
using myset = std::set<unsigned, decltype<compare>*>;
class BadSet
public:
...
myset Set2 = mysetcompare;
or
myset Set2 = myset(compare);
...
;
或大括号初始化器:
class BadSet
public:
...
std::set<unsigned, decltype<compare>*> Set2compare;
...
;
更多详情请见Non-static data members。
另见Using custom std::set comparator
【讨论】:
以上是关于std::set 作为类成员不能使用函数指针作为 key_comp的主要内容,如果未能解决你的问题,请参考以下文章