I need to call a method that expects a function pointer, but what I really want to pass to it is a functor. Here's an example of what I'm trying to do:
#include <iostream>
#include "boost/function.hpp"
typedef int (*myAdder)(int);
int adderFunction(int y) { return(2 + y); }
class adderClass {
public:
adderClass(int x) : _x(x) {}
int operator() (int y) { return(_x + y); }
private:
int _x;
};
void printer(myAdder h, int y) {
std::cout << h(y) << std::endl;
}
int main() {
myAdder f = adderFunction;
adderClass *ac = new adderClass(2);
boost::function1<int, int> g =
std::bind1st(std::mem_fun(&adderClass::operator()), ac);
std::cout << f(1) << std::endl;
std::cout << g(2) << std::endl;
printer(f, 3);
printer(g, 4); // Is there a way to get this to work?
}
I haven't been able to find a way to get the last line, printer(g, 4), to compile. Is there a way to get this to work? The only things in my control are the method "main" and the class "adderClass".
Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);
You can use pointers to member functions in the same manner as pointers to functions.
You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions. For z/OS® XL C/C++, use the __cdecl keyword to declare a pointer to a function as a C linkage.
Functions Using Pointer Variables C allows pointers to be passed in as function arguments and also return pointers from the function. To pass pointers in the function, we simply declare the function parameter as pointer type.
Ok, here's another try:
class CallProxy
{
public:
static adderClass* m_instance;
static int adder(int y)
{
return (*m_instance)(y);
}
};
adderClass* CallProxy::m_instance = NULL;
int main() {
myAdder f = adderFunction;
adderClass ac(2);
std::cout << f(1) << std::endl;
std::cout << ac(2) << std::endl;
printer(f, 3);
CallProxy::m_instance = ∾
printer(CallProxy::adder, 4);
}
The trouble is that you have printer
compiled as having to receive a function pointer and nothing else so you must send it a function pointer. With a function pointer you have no one to hold your instance. So this solution does that by using a static data member.
Mind you that this makes this code not thread safe. Two threads which execute main
at the same time may put two different things in m_instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With