Function Member Pointer

I am trying to do something with pointers to functions that I cannot understand how this works.

I have a class A that looks something like this:

class A
{
    public:
    float Plus    (float a, float b) { return a+b; }
    float Minus   (float a, float b) { return a-b; }
    float Multiply(float a, float b) { return a*b; }
    float Divide  (float a, float b) { return a/b; }
};

I want to declare a pointer to A, and then pass another function pointer to a function pointer to one of A.

Something like:

void Will_Get_Function_Pointer(float a, float b, float (A::*pt2Func)(float, float))
{
    (...)
}

Where I would call it something like this

A* myA = new A;
Will_Get_Function_Pointer(1.00,2.00, &myA->Minus)

I cannot use static / const elements because in my last implementation A will point to a specific A in the collection of objects A in something that will look like

vector<A> vecA;
myA = &vecA[xxx]

Doing this fails

typedef  float (A::*pA)(float x, float y);
pA p = &myA->Minus;

and the compiler tells me to use & A :: Minus, but this will not work for me.

Can I do it?

Greetings

+5
source share
3 answers
A* myA = new A;
Will_Get_Function_Pointer(1.00,2.00, &myA->Minus)

You can not. You should use something like

void Will_Get_Function_Pointer(A* object, float a, float b,
float (A::*pt2Func)(float, float))
{
   (object->*pt2Func)(a, b);
}

A* myA = new A;
Will_Get_Function_Pointer(myA, 1.00, 2.00, &A::Minus);

.

http://liveworkspace.org/code/79939893695e40f1761d81ba834c5d15

+6

, - . ( ) :

void Will_Get_Function_Pointer(float a, float b, A & obj, float (A::*pt2Func)(float, float))
{
    (obj.pt2Func)(a,b);
}

Will_Get_Function_Pointer(1.00, 2.00, myA, &A::Minus);

, :

void Will_Get_Function(float a, float b, std::function<float(float,float)> f)
{
    f(a,b);
}

Will_Get_Function(1.00, 2.00, std::bind(&A::Minus, &myA));

, function bind ++ 11; Boost , .

+2

Use macro.

#define CALL_MEMBER_FN(object,ptrToMember)  ((object).*(ptrToMember))

Calling a member function is simple because you already have a typedef for the function you want to call.

float result = CALL_MEMBER_FN(*myA, pA)(a, b);
+2
source

All Articles