【问题标题】:C++11 : How to use std::mem_fn and std::bind with inheritanceC++11:如何使用 std::mem_fn 和 std::bind 继承
【发布时间】: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(&amp;Derived::memberFunc, this, _1)); 的语法吗?无关,您的invokeFunc 有点费力,可能只是return functionTable_[name](arg);
  • 我认为您正在尝试做的事情在这里解释:en.cppreference.com/w/cpp/language/…
  • @Casey - 你的回答奏效了!请提交作为解决方案,我将选中该框以给予您信用。谢谢!

标签: c++ c++11 lambda bind member


【解决方案1】:

首先你的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");
}

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 2012-05-20
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2012-10-27
    • 1970-01-01
    相关资源
    最近更新 更多