I have difficulty to map the functions of the class member inside the class itself
#include <functional>
#include <map>
#include <string>
class Foo{
public:
void bar() {}
void jar() {}
private:
std::map<std::string, std::function<void(void)>> myMap =
{
{"bar", bar},
{"jar", jar}
};
};
The compiler says no
Severity Code Description Project File Line Suppression State Suppression State Error (active) E0289 no instance of constructor "std::map<_Kty, _Ty, _Pr, _Alloc>::map [with _Kty=std::string, _Ty=std::function, _Pr=std::less, _Alloc=std::allocator>>]" matches the argument list Stackoverflow C:\Stackoverflow\Foo.h 13
Please help, thank you.
bar
and jar
are member functions. They take pointer - this
as first hidden parameter, you cannot treat them as free-functions. And you cannot just wrap them into function<void(void)>
by taking pointers to them - what you are doing now.
You should use std::bind
to bind this
to member functions (or use lambda expressions):
std::map<std::string, std::function<void(void)> > myMap2 =
{
{"bar", std::bind(&Foo::bar,this)},
{"jar", std::bind(&Foo::jar,this)}
};
or store pointers to functions:
std::map<std::string, void (Foo::*)(void) > myMap =
{
{"bar", &Foo::bar},
{"jar", &Foo::jar}
};