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

1.6k Views Asked by At

I have the following setup:

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}
    };
}

But I always get the error:

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

What is wrong with my initalizer list?

1

There are 1 best solutions below

0
On BEST ANSWER

Your question is missing a MCVE, however the error message is clear enough: reaction seems to be a typedef for std::function<void()>. A member function pointer such as &Node::connect cannot be converted to a std::function<void()>, because the latter lacks any kind of this parameter upon which to actually call the function.

You can, however, use lambdas to capture and store the instance that is currently initializing this TransTable member:

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