user2022185
user2022185

Reputation: 127

How do I insert a member-function pointer into a map?

I have this map:

std::map<std::string, std::function<void (std::string)>> cMap;

I don't quite understand how to add value to it?

I tried

cMap.insert(std::make_pair("test", &Manager::testfunc));

And

cMap["test"] = &Manager::testfunc;

But I get "failed to specialize function template" errors on either one.

I'm not all that familiar with function pointers and I've honestly spent hours googling and reading questions and answers, but I just can't find anything that works. Please help me.

Edit: For now, Manager::testfunc is just:

void Manager::testfunc (std::string value) { }

Upvotes: 2

Views: 147

Answers (1)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42899

In order for a member function pointer to be callable you must bind it to an object. Thus, provided a Manager object (e.g., Manager m) you can use std::bind to bind a member function (e.g., void Manager::foo(std::string const&)) and then insert it in your std::map as follows:

struct Manager {
  void foo(std::string const& str) { std::cout << str << std::endl; }
};

int main() {
  std::map<std::string, std::function<void(std::string const&)>> cMap;
  Manager m;
  cMap.insert(std::make_pair("test", std::bind(&Manager::foo, &m, std::placeholders::_1)));
  cMap["test"]("Hello, world!");
}

LIVE DEMO

Upvotes: 2

Related Questions