我想知道如何将“this”指针传递给类中的方法。 让我们看看这段代码:
class CTest
{
public:
CTest(int n_) : n(n_) {}
void method()
{
std::cout << n << std::endl;
}
private:
int n;
};
int main()
{
CTest t1(100);
boost::bind(&CTest::method, &t1)(); //100
boost::bind(&CTest::method, _1)(&t1); //100
Test::method(&t1); //no matching function for call to ‘CTest::method(CTest*)’
return 0;
}
假设绑定(bind)就像函数对象一样工作,它会以某种方式传递 this/object 指针。如果我想明确地这样做,我会得到一个编译错误。
它实际上是如何工作的?
最佳答案
boost::bind
识别它包装的目标何时是指向成员的指针,并使用不同的代码路径调用它,使用指向成员的指针的正确语法。
与编程中的大多数问题一样,您可以通过添加一个间接级别来解决它。 bind
可以对其目标应用转换,以便将指向成员的指针调整为可以像普通函数对象一样调用的东西,并处理细节,所以 bind
本身不需要知道细节。
函数 boost::mem_fn
可用于将指向成员的指针转换为可调用对象:
void (CTest::*memptr)() = &CTest::method;
CTest* p = &t1;
auto callable = boost::mem_fn(memptr);
callable(p); // calls (p.->*memptr)()
因此给定适配器,bind
只需要确保在需要时使用它即可。
在 GCC 实现中,我们有这样的东西:
template<class T>
struct maybe_wrap_mem_ptr
{
typedef T type;
};
// partial specialization for pointer to member
template<class R, class C>
struct maybe_wrap_mem_ptr<R C::*>
{
typedef mem_fn_wrapper<R C::*> type;
};
template<class T>
typename maybe_wrap_mem_ptr<T>::type
wrap_mem_ptr(T t)
{ return typename maybe_wrap_mem_ptr<T>::type(t); }
其中 mem_fn_wrapper
是 std::mem_fn
函数返回的类型。所以bind
可以只用wrap_mem_ptr
来保证它包裹的对象可以被统一调用。
关于c++ - 指向方法的指针/传递此指针/boost::bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25056420/