我需要有一个基类能够存储指向成员函数的指针,不仅可以用于它自己的方法,也可以用于子类。这是我想要使用 LAMBDAS 的示例,但我希望能够使用成员函数来完成它:
struct Base
{
void registerFunc(std::string const& name, std::function<void *(void *)> code)
{
functionTable_[name] = code;
}
void *invokeFunc(std::string const& name, void *arg)
{
auto x = functionTable_[name];
auto func = std::bind(x, _1);
return func(arg);
}
Base()
{
registerFunc("hello", [this](void *arg) { printf("hello"); return nullptr; });
invokeFunc("hello");
}
private:
std::unordered_map<std::string, std::function<void *(void *)>> functionTable_;
};
struct Derived : Base
{
Derived()
{
registerFunc("world", [this] (void *arg) { printf("world"); return nullptr; });
invokeFunc("world");
}
// Instead of lambdas, I would like to be able to put member
// functions like this into the std::unordered_map of the Base class
void *memberFunc(void *arg) { printf("oyoyoy"; }
};
最佳答案
首先,您的 invokeFunc
方法不需要使用 std::bind()
并且至少应该检查函数是否存在:
void *invokeFunc(std::string const& name, void *arg)
{
auto &x = functionTable_[name];
if( !x ) return 0;
return x(arg);
}
但更好的方法是使用 std::map::find()
我相信
其次你可以使用std::bind()
来传递方法:
Derived()
{
registerFunc("world", [this] (void *arg) { printf("world"); return nullptr; });
invokeFunc("world");
registerFunc("method", std::bind( &Derived::memberFunc, this, _1 ) ) );
invokeFunc("method");
}
关于C++11:如何通过继承使用 std::mem_fn 和 std::bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21117176/