|
I want to set the function pointer at runtime. But i'm stuck here. When i use global function or static class member function, everything is ok. but, when the function is ordinary class member functions. i always got compiler errors. Here is the code:
class A
{
int val;
public:
A() { val = 0; }
A(int j) { val = j; }
int aFun(int k) {val -= k; return val; }
};
typedef int (* func)(int );
class B
{
func m_addr;
public:
B(func param)
: m_addr(param)
{
}
void execute()
{
cout << m_addr(9) << endl;
}
};
I'm trying to use them like this:
A a;
B b(A::aFun);
b.execute();
after googled a lot, i found that std::mem_fun may be helpful. but i don't know how to use it. anyone can help me?
PS: i'm using Visual C++ 2010
|
|
|
|
|
I think the function needs to be a class function (i.e. static ).
One of these days I'm going to think of a really clever signature.
|
|
|
|
|
The code doesn't make a lot of sense. The is no connection between the member function to be called and a specific instance of A on which to call it. Also the typedef is incorrect for a non-static member function, make it look likes this:
typedef int (* A::func)(int );
Steve
|
|
|
|
|
A::aFun is different from func.
|
|
|
|
|
When you think about it, what you try to achieve isn't logically possible:
A member function that is not static implicitely takes a pointer to the instance as it's first (hidden) argument, so you cannot encode that as a simple pointer, as you always have to additionally pass that instance-pointer. Class B does not have a pointer to an instance of class A, so it cannot possibly call a member function, whether by pointer or any other mechanic!
When you look at your code, where do you use the object a ? Nowhere!
|
|
|
|
|
|
thank you very much. the command pattern is the perfect solution.
|
|
|
|