无法为 std::map 中的 std::pair 转换大括号括起来的初始值设定项列表

Could not convert brace enclosed initializer list for std::pair in std::map

我有以下设置:

typedef std::function<void()> reaction;

class Node
{
  public:
  ...

  private:
    void connect();
    void receive();

  private:
    const std::map<std::pair<Status, Event>, reaction> TransTable = {
      {{DISCONNECTED, CONNECT}, &Node::connect},
      {{CONNECTING, RECEIVE}, &Node::receive}
    };
}

但我总是得到错误:

error: could not convert from <brace-enclosed initializer list> to const std::map<std::pair<Status, Event>, std::function<void()> >

我的初始化列表有什么问题?

您的问题缺少 MCVE,但是错误消息很清楚:reaction 似乎是 std::function<void()> 的类型定义。 &Node::connect 之类的成员函数指针不能转换为 std::function<void()>,因为后者缺少任何类型的 this 参数来实际调用函数。

但是,您可以使用 lambda 来捕获和存储当前正在初始化此 TransTable 成员的实例:

const std::map<std::pair<Status, Event>, reaction> TransTable = {
  {{DISCONNECTED, CONNECT}, [this] { connect(); }},
  {{CONNECTING,   RECEIVE}, [this] { receive(); }}
};