我是 C++ 的新手。我想制作一个 std::map,其中的 get-method 名称字符串映射了它们各自的 get-method。这些将被循环并显示通过 get-method 获得的值以及方法名称。我将遍历 A 类型的几个实例。我发现 boost/function 对于在 A 中存储 get 方法非常有用。但是,A 也有一个 B 类型的实例,它有自己的 get 方法。如何访问 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");
}
最佳答案
// 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(); }
关于c++ - 指向函数指针返回的对象实例的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25801131/