Martin G
Martin G

Reputation: 18129

How to pass a function pointer to overloaded member function as parameter

This is related to code generation.

I have a class A which is generated from model, in which I have two overloads of function f like below:

class A
{
  public:
    void f(int a){}
    void f(int a, int b){}
}

I then have a separate part of the system which is not generated from model, but written in hand crafted C++. Here I would like to access the function f on an object. From the model I can pass data to the hand crafted part of the system, but not the other way around, since the generated file is not available for compilation when I build my hand crafted code.

My idea is to pass a function pointer from the model to where I need it. This, as I have understood it so far, includes static_cast to solve the overload issue and then I can pass a pointer to the function as a parameter to some other hand crafted function.

The function used to pass the pointer to the hand crafted part of the system is declared like this (here A is not known):

void passPointer(int, void (*f)(int, int));

My cast and function call looks like:

handCraftedObject->passPointer(17, static_cast<void (A::*)(int, int)> (&A::f) );

My compilation error is:

:   no known conversion for argument 2 from 'void (A::*)(int, int)' to 'void (*)(int, int)

I hope this doesn't mean i have to know the class A where the function passing the function pointer is declared. This is not possible in my system.

Upvotes: 0

Views: 591

Answers (1)

ForEveR
ForEveR

Reputation: 55897

Member function pointer has different type than function pointer and cannot be converted to it. The simplest way is to use boost/std(C++11) bind and function.

void passPointer(int, const std::function<void(int, int)>&);

than just

handCraftedObject->passPointer
(
   17, std::bind(static_cast<void (A::*)(int, int)> (&A::f), std::ref(a_instance), 
   std::placeholders::_1, std::placeholders::_2)
);

Also you cannot use boost/C++11, you can make function f static, then all will works fine.

Upvotes: 2

Related Questions