André Moreira
André Moreira

Reputation: 1699

pointer to function member

I'm trying to do something with pointers to function members that I cant' figure out 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 to another function a function pointer to one of the members of A.

Something likes this:

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

Where I would call it with something like this

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

I can't use static/const members because In my final implementation A will point to a specific A in a collection of A objects in something that will look like this

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

Doing this fails miserably

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

and the compiler tells me to use &A::Minus but that wont work for me.

Can I even do this?

Cheers

Upvotes: 5

Views: 354

Answers (3)

Michael Kristofik
Michael Kristofik

Reputation: 35178

Use a macro.

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

Calling your 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);

Upvotes: 2

Mike Seymour
Mike Seymour

Reputation: 254431

Unfortunately, the language doesn't allow you to use that syntax to bind an object to member function to make a callable object. You can either pass in an object reference (or pointer) and bind it when you call the function:

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);

Or you can create a function object that binds the function pointer to the object:

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));

Note that function and bind are new in C++11; Boost provides equivalents if you're stuck with an old version of the language.

Upvotes: 2

ForEveR
ForEveR

Reputation: 55887

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

You cannot. 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);
}

And calls it as

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

Simple example.

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

Upvotes: 6

Related Questions