【发布时间】:2014-01-14 15:22:13
【问题描述】:
我需要有一个基类,它可以存储指向成员函数的指针,不仅用于它自己的方法,还用于子类。这是我想要使用 LAMBDAS 的示例,但我希望能够使用 MEMBER FUNCTIONS 来做到这一点:
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"; }
};
【问题讨论】:
-
我在你的基类中没有看到虚函数。您是否尝试使用多态性?
-
不,我不是在尝试使用多态性——尽管 functionTable_ 的用途与我知道的 v-table 非常相似。考虑通过网络接收到的一条数据导致执行其中一个函数(“hello”或“world”)的情况。您不能为此使用 v-table,您基本上必须自己构建。
-
您在寻找
registerFunc("world", std::bind(&Derived::memberFunc, this, _1));的语法吗?无关,您的invokeFunc有点费力,可能只是return functionTable_[name](arg);。 -
我认为您正在尝试做的事情在这里解释:en.cppreference.com/w/cpp/language/…
-
@Casey - 你的回答奏效了!请提交作为解决方案,我将选中该框以给予您信用。谢谢!
标签: c++ c++11 lambda bind member