c++ - 是否可以 boost::bind 到已知类但(尚)未知对象的成员函数?

标签 c++ boost c++11 bind dispatch

我已阅读here关于 boost:bind 是如何工作的,尤其是它 - 除了其他东西 - 生成这样的东西:

struct unspecified_type
{
  ... some members ...
  return_type operator()(int i) const { return instance->*&klass::member(0, i);
}

现在,我正在寻找允许向实例指针添加额外间接的东西,以便它最终看起来像这样:

struct unspecified_type
{
  ... some members ...
  return_type operator()(int i) const { return (*p_instance)->*&klass::member(0, i);
}

可以像这样使用

MyClass* pmc;
auto mfp = boost::bind(&MyClass::some_func, &pmc);
pmc = new MyClass();
mfp();
pmc = new MyClass();
mfp();

最佳答案

您可以使用 std::bindstd::ref 或它们的 boost 等效项(但由于您使用的是 C++11,因此您可能需要使用标准类和函数)。所以给定这个类:

#include <iostream>

struct MyClass
{
    int x;
    MyClass(int x_) : x(x_) { }
    void some_func()
    {
        std::cout << x << std::endl;
    }
};

您可以传递将要调用的成员函数封装在 std::reference_wrapper 中的指针。另外,避免使用new(和delete!),而更喜欢使用智能指针来建模对象所有权:

#include <functional>
#include <memory>

int main(int argc, char *argv[])
{
    std::shared_ptr<MyClass> pmc;
    auto mfp = std::bind(&MyClass::some_func, std::ref(pmc));

    pmc = std::make_shared<MyClass>(42);
    mfp();

    pmc = std::make_shared<MyClass>(1729);
    mfp();
}

这是一个live example .

关于c++ - 是否可以 boost::bind 到已知类但(尚)未知对象的成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16608723/

相关文章:

c++ - 将 boost 间隔扩展到标量乘法

c++ - 如何在 boost C++ 中对具有多个参数的函数使用二分方法

c++ - 如何创建 union 类结构?

c++ - 将 lambda 传递给 std::thread 并调用类方法

c++ - 如何重写参数 `const T&` 和 `T&&` 的通用函数,其中 T 可以作为引用?

c++ - OpenGL 谷歌地图样式 2D 相机/缩放到鼠标光标

c++ - GUI 应用程序中的 QPainter 错误

c++ - 如何使用 CMake 将 NMake 从 VS9 切换到 VS10

c++ - 图的链表实现

c++ - 空结构是由 C++ 标准定义的吗?