【问题标题】:std::set as a class member can't use function pointer as key_compstd::set 作为类成员不能使用函数指针作为 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&lt;unsigned, decltype&lt;compare&gt;*&gt; Set2{compare};
  • 谢谢! Set2{compare} 有效。但是为什么类中的 std::set 定义需要不同的语法呢?
  • @wuyabiao -- 仔细看看你的尝试。如何构造一个需要使用括号(不是大括号)参数的类成员对象?您将需要使用成员初始化列表。另请注意,如果您有struct B { B(int) {} }; 并尝试将B 作为BadSet 的类成员,您也会遇到同样的问题。所以问题与std::set无关。

标签: c++ function pointers stdset


【解决方案1】:

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

  • 使用父类构造函数的成员初始化列表:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 2015-10-01
    相关资源
    最近更新 更多