Reputation: 7
Im new to c++. I want to make a std::map with strings of get-method names mapped their respective get-method. These are to be looped over and present the value obtained by the get-methodtogether with the method name. I will loop over several instances of the type A. I have found that boost/function is very useful for storing the get-methods in A. However, A also has an instance of type B, with its own get-methods. How do I access the get-method in B?
Here is my current code (The line mapping["B_Nine"] = &B::(&A::getB)::nine
is wrong, but my best guess so far)...
#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");
}
Upvotes: 1
Views: 81
Reputation: 462
// 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);
or
mapping["B_Nine"] = [] (A *a) { return a->getB().nine(); }
Upvotes: 3