![](/img/trans.png)
[英]boost::bind() a member function to boost::function with object pointer as placeholder?
[英]Getting object that contains the member function from boost function created with bind
void someFunction(boost::function<void()> func)
{
... //Get myObj
}
MyClass *myObj = ...;
someFunction(boost::bind(&MyClass::memberFunction, myObj));
我如何从函数内部获取指向myObj的指针或引用void someFunction
通常,从绑定结果中提取用作boost::bind
(或std::bind
)参数的对象是不可能的,也不希望这样做。 结果对象的存储方式是特定于实现的。
观察如何在文档中将其定义为未指定 (请参见下面的链接):
// one argument
template<class R, class F, class A1> unspecified-3 bind(F f, A1 a1);
为了进一步说明,请在同一页面上查看此段:
即使函数对象是一元或二进制操作,通过boost :: bind生成的函数对象也不会对STL一元函数或二进制函数概念建模, 因为函数对象类型缺少公共类型 ,def,result_type和arguments_type或first_argument_type和second_argument_type 。 但是,在需要这些类型定义的情况下,可以使用实用程序functionmake_adaptable使一元和二进制函数对象适应这些概念。
http://www.boost.org/doc/libs/1_55_0/libs/bind/bind.html#CommonDefinitions
库开发人员明确地告诉您,返回的类型是不透明的,不会给您返回传入的参数的类型,也不打算让您从不透明的绑定返回类型中获取对象。
但是,当您调用bind()时,是由您提供参数的,因此您可以将它们存储在一边,以后再使用。 另外,如注释中所建议,当绑定方法被调用时,您可以仅使用*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 */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.