![](/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.