我是c ++的新手。我想创建一个std :: map,其中get-method名称字符串映射到它们各自的get-method。这些将循环并通过方法名称显示get-methodtogether获得的值。我将遍历几个类型A的实例。我发现boost / function对于在A中存储get方法非常有用。但是,A也有一个B类实例,它有自己的get-methods。如何在B中访问get方法?
这是我当前的代码(行mapping["B_Nine"] = &B::(&A::getB)::nine
错了,但到目前为止我最好的猜测)......
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <iostream>
#include <map>
#include <string>
#include <functional>
class B
{
public:
B();
~B();
int nine() {return 9;}
};
B::B()
{
}
B::~B()
{
}
class A
{
public:
A();
~A();
int one () {return 1;}
int two () {return 2;}
B getB() {return b;}
B b;
};
A::A()
{
b = B();
}
A::~A()
{
}
typedef std::map<std::string,boost::function<int (A*)>> str_func_map;
int main()
{
str_func_map mapping;
mapping["One"] = &A::one;
mapping["Two"] = &A::two;
mapping["B_Nine"] = &B::(&A::getB)::nine //This line is wrong - how should
//it be done correctly??
A* a = new A();
for (str_func_map::iterator i = mapping.begin(); i != mapping.end(); i++)
{
std::cout<< i->first << std::endl;
std::cout<< (i->second)(a) << std::endl;
}
system("pause");
}
答案 0 :(得分:3)
// free function
int callMethodOfB(A *a, std::function<int(B*)> method) {
return method(&(a->getB()));
}
mapping["B_Nine"] = std::bind<int>(&callMethodOfB, std:placeholder::_1, &B::nine);
或
mapping["B_Nine"] = [] (A *a) { return a->getB().nine(); }