【问题标题】:Getting object that contains the member function from boost function created with bind从使用 bind 创建的 boost 函数中获取包含成员函数的对象
【发布时间】:2014-01-11 04:09:47
【问题描述】:
void someFunction(boost::function<void()> func)
{
    ... //Get myObj
}
MyClass *myObj = ...;
someFunction(boost::bind(&MyClass::memberFunction, myObj));

如何从函数 void someFunction 中获取指向 myObj 的指针或引用

【问题讨论】:

  • 为什么不简单地将 ref 传递给对象?
  • @billz 你的意思是在 boost::function func 之后将它作为第二个参数传递吗?我正在尝试制作 boost::signals 类型的连接功能。 Boost 不需要通过 myObj 两次。主要是为了保持参数简短。
  • 不清楚您要完成什么,但是一旦参数已绑定到函数,您就无法访问它们。
  • @EricFortin 我不是在谈论如何获取参数,我是在问如何获取用于调用成员函数的对象。 boost::bind(&MyClass::memberFunction, myObj)() 会调用 myObj->memberfunction(),如何获取 myObj 的指针或引用
  • myObj 是传递给您的成员函数的第一个参数。这就是成员函数的工作原理。

标签: c++ boost boost-bind boost-function


【解决方案1】:

通常不可能也不希望从绑定结果中提取用作boost::bind(或std::bind)的参数的对象。结果对象的存储方式是特定于实现的。

观察它是如何在文档中定义为未指定的(见下面的链接):

// one argument
template<class R, class F, class A1> unspecified-3 bind(F f, A1 a1);

为了进一步说明,请看同一页上的这段:

boost::bind 生成的函数对象不建模 STL 一元函数或二元函数概念,即使函数 对象是一元或二元运算,因为函数对象 类型缺少公共类型定义 result_type 和 argument_type 或 first_argument_type 和 second_argument_type。在这些情况下 typedef 是可取的,但是,实用函数make_adaptable 可用于使一元和二元函数对象适应这些 概念。

http://www.boost.org/doc/libs/1_55_0/libs/bind/bind.html#CommonDefinitions

库开发人员明确告诉您返回的类型是不透明的,不会返回您传入的参数的类型,也不打算让您从不透明绑定中获取对象返回类型。

但是,当您调用 bind() 时,是您提供参数,因此您可以将它们存储在一边,以便以后使用。或者,正如 cmets 中所建议的,您可以在调用绑定方法时使用 *this 作为对被调用者的引用。

#include <boost/bind.hpp>
#include <iostream>

struct Foo {
    void f() const {
       const Foo& myObj = *this;
       std::cout << "Invoked  instance: " << std::hex << &myObj << std::endl;
    }
};

int main() {
    Foo foo;
    std::cout << "Invoking instance: " << std::hex << &foo << std::endl;
    boost::bind(&Foo::f, boost::ref(foo))();
    return 0;
}
/* Output:
Invoking instance: 0x7fff4381185f
Invoked  instance: 0x7fff4381185f */

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 2013-09-21
    • 2021-07-10
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    相关资源
    最近更新 更多