C++11:如何通过继承使用 std::mem_fn 和 std::bind

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

我需要有一个基类能够存储指向成员函数的指针,不仅可以用于它自己的方法,也可以用于子类。这是我想要使用 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/

相关文章:

c++ - 有没有合理的替代重载和完美转发的方案?

c++ - 成员初始化列表中的 unique_ptr

lambda 表达式中的 C# 未检查关键字

c# - 使用 lambda 返回连接的字符串

c++ - 使用 MHook 的系统范围的钩子(Hook)

c++ - 使用 Curiously Recursive Template Pattern 在子类之间进行转换

c++ - 使用依赖于 lambda 函数的类型作为返回类型

java - Lambda 表达式中方法引用的方法引用

java 和 C++11 volatile

C++ 二维 vector 和操作