Joh*_*0te 5 c++ member-function-pointers function-pointers c++03
是否可以声明一个可以指向任何类的成员函数的函数指针(非 C++ 11)(阅读:不是特定的类)?
例如,如果我有类 A、B 和 C。C 中声明了一个函数指针,我想在指向 B 的成员函数之一和 A 的成员函数之一之间切换该指针。C++ 允许这样做吗?
是的,你可以,但你必须删除一些类型安全并跟踪this指针以及成员函数。
您可以在http://www.codeproject.com/Articles/11015/The-Impossively-Fast-C-Delegates 中看到一个用例。基本思想是将对象指针存储为空指针,并通过静态方法重定向函数调用。
#include <iostream>
using namespace std;
struct A { void foo() { cout << "A::foo\n"; } };
struct B { void foo() { cout << "B::foo\n"; } };
class C
{
public:
C() : object_ptr(0), stub_ptr(0) {}
template <class T, void (T::*TMethod)()>
static C from_method(T* object_ptr)
{
C d;
d.object_ptr = object_ptr;
d.stub_ptr = &method_stub<T, TMethod>;
return d;
}
void operator()() const
{
return (*stub_ptr)(object_ptr);
}
private:
typedef void (*stub_type)(void* object_ptr);
void* object_ptr;
stub_type stub_ptr;
template <class T, void (T::*TMethod)()>
static void method_stub(void* object_ptr)
{
T* p = static_cast<T*>(object_ptr);
return (p->*TMethod)();
}
};
int main()
{
A a;
B b;
C c = C::from_method<A, &A::foo>(&a);
c();
c = C::from_method<B, &B::foo>(&b);
c();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码应该打印
A::foo
B::foo
Run Code Online (Sandbox Code Playgroud)
此解决方案比使用更快,std::function因为它不需要为数据分配堆存储,但这可能仅用于引用成员函数(与std::function声明任何可调用对象的所有权不同)。
boost::function能够与以下命令一起执行此操作boost::bind:
#incluce <boost/function.hpp>
#include <boost/bind.hpp>
struct A{ void f(); };
struct B{ void g(); };
struct C{
boost::function<void()> _func;
};
int main(){
A a; B b; C c;
c.func = boost::bind(&A::f, &a);
c.func();
c.func = boost::bind(&B::g, &b);
c.func();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1424 次 |
| 最近记录: |