What I wish to do is have a class that contains a map of function pointers of a second class, but the name of the second class should not matter (cannot be hard coded into the first class) I would really like to be able to implement this WITHOUT using macros. I have followed the examples from learncpp.com on function pointers, but when passing them between classes I am really lost! My attemp开发者_如何学运维t is below:
#include <map>
class Class1;
typedef double(Class1::*memFunc)();
class Class1
{
private:
std::map<std::string, memFunc> funcMap;
public:
void addFunc(std::string funcName, memFunc function)
{
funcMap.insert(std::pair<std::string, memFunc>(funcName, function));
}
};
class MyClass
{
public:
MyClass()
{
//How do I add member function getValue() to Class1?
class1.addFunc("new function", getValue());
}
double getValue()
{
return 0;
}
private:
Class1 class1;
};
The name of the class is a part of the type of the function pointer, which becomes part of the map's type, which becomes part of MyClass. Depending on how strong is the requirement "cannot be hard coded", perhaps a template would be sufficient?
#include <string>
#include <map>
template<typename T>
class Class1
{
typedef double(T::*memFunc)();
std::map<std::string, memFunc> funcMap;
public:
void addFunc(std::string funcName, memFunc function)
{
funcMap.insert(std::pair<std::string, memFunc>(funcName, function));
}
};
class MyClass
{
public:
MyClass()
{
class1.addFunc("new function", &MyClass::getValue);
}
double getValue()
{
return 0;
}
private:
Class1<MyClass> class1;
};
int main()
{
MyClass mc;
}
精彩评论