调用特定对象实例上的C ++函数指针 [英] Calling a C++ function pointer on a specific object instance
问题描述
我有一个定义的函数指针:
typedef void(* EventFunction)(int nEvent);有没有办法用一个C ++对象的特定实例来处理这个函数? class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func){handler = func; }
void EventOne(){handler(1); }
};
class B
{
private:
A a;
public:
B(){a.SetEvent(EventFromA); } //我在这里做什么?
void EventFromA(int nEvent){// do stuff}
};
编辑:Orion指出了Boost提供的选项,例如: / p>
boost :: function< int(int)> F;
X x;
f = std :: bind1st(
std :: mem_fun(& X :: foo),& x);
f(5); //调用x.foo(5)
不幸的是Boost对我来说不是一个选择。是否有某种类型的currying函数可以用C ++编写,将这样包装成一个成员函数的指针到正常的函数指针?
解决方案我强烈推荐Don Clugston的出色的FastDelegate库。它提供了所有你期望的一个真正的委托,编译下来几个ASM指令在大多数情况下。附带的文章也是一个很好的成员函数指针。
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
I have a function pointer defined by:
typedef void (*EventFunction)(int nEvent);
Is there a way to handle that function with a specific instance of a C++ object?
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne() { handler(1); }
};
class B
{
private:
A a;
public:
B() { a.SetEvent(EventFromA); } // What do I do here?
void EventFromA(int nEvent) { // do stuff }
};
Edit: Orion pointed out the options that Boost offers such as:
boost::function<int (int)> f;
X x;
f = std::bind1st(
std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)
Unfortunately Boost is not an option for me. Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?
解决方案 I highly recommend Don Clugston's excellent FastDelegate library. It provides all the things you'd expect of a real delegate and compiles down to a few ASM instructions in most cases. The accompanying article is a good read on member function pointers as well.
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
这篇关于调用特定对象实例上的C ++函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!