我想在初始化映射时使用std::function<void()>
作为类型名:
namespace kc
{
class kcmessage
{
private:
std::string value;
void warning() {}
void error()
{
exit(1);
}
std::map<std::string, std::function<void()>> msgtypes = {
{ "WARNING", warning },
{ "ERROR", error }
};
int msgtype;
};
}
但它不起作用:error: could not convert ‘{{"WARNING", ((kc::kcmessage*)this)->kc::kcmessage::warning}, {"ERROR", ((kc::kcmessage*)this)->kc::kcmessage::error}}’ from ‘<brace-enclosed initializer list>’ to ‘std::map<std::__cxx11::basic_string<char>, std::function<void()> >’
(<brace-enclosed initializer list>
(
如果要访问成员函数(非静态(,必须将该方法绑定到类的实例。为此,您可以使用std::bind
,但为此目的简单地使用lambda要容易得多。
#include <functional>
#include <map>
#include <string>
#include <iostream>
namespace kc
{
class kcmessage
{
private:
std::string value;
void warning() {std::cout << "Waring called!"<<std::endl;}
void error()
{
std::cout << "Error called" << std::endl;
//exit(1);
}
std::map<std::string, std::function<void()>> msgtypes = {
{ "WARNING", [this](){ warning();} },
{ "ERROR", [this](){ error();} }
};
int msgtype;
public:
void CallAll()
{
for( auto& el: msgtypes)
{
el.second();
}
}
};
}
int main()
{
kc::kcmessage{}.CallAll();
}
在此处执行
您可以使您的方法也成为static
方法,但在这种情况下,如果需要,您将无法再访问您的成员数据,这是典型的情况。