【问题标题】:Is it possible to boost::bind to a member function of a known class but a (yet) unknown object?是否可以将 boost::bind 绑定到已知类的成员函数但(尚未)未知对象?
【发布时间】:2013-05-12 14:28:15
【问题描述】:

我已阅读 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();

【问题讨论】:

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


    【解决方案1】:

    您可以使用std::bindstd::ref,或它们的等效项(但由于您使用的是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

    【讨论】:

      【解决方案2】:

      从技术上讲,您可以使用 get_pointer 函数扩展 boost::bind(但不是 std::bind):

      #include <boost/bind.hpp>
      struct MyClass
      {
        void some_func()
        {}
      };
      
      namespace boost
      {
        template<class T>
        T *get_pointer(T **t)
        {
          return *t;
        }
      }
      
      int main()
      {
        MyClass *pmc;
        auto mfp = boost::bind(&MyClass::some_func, &pmc);
        pmc = new MyClass();
        mfp();
        pmc = new MyClass();
        mfp();
      }
      

      【讨论】:

      • 嗨,伊戈尔。这就是我首先想到的(对它了解不多),我认为这可能是一种探索性方法的更直观的解决方案,不过,我更喜欢 Andy 的解决方案,因为它的语义似乎更标准,并且使用现有的类型,但会在其他一切都无济于事的事件中记住您的类型。
      猜你喜欢
      • 1970-01-01
      • 2016-02-13
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2012-12-14
      相关资源
      最近更新 更多