Setting a pointer to a non-static member function - c++

I'm trying to setup a function pointer that is set during execution based on a set of user parameters. I would like to have the function pointer point to a non-static member function but I can't find how to do it.
The examples I've seen say this can only be done with static member function only or use global variables in straight C.
A simplified example follows:
class CA
{
public:
CA(void) {};
~CA(void) {};
void setA(double x) {a = x; };
void setB(double x) {b = x; };
double getA(const double x) {return x*a; };
double getB(const double x) {return x*b; };
void print(double f(const double), double x) {
char cTemp[256];
sprintf_s(cTemp, "Value = %f", f(x));
std::cout << cTemp;
};
private:
double a, b;
};
The implementation part is
CA cA;
cA.setA(1.0);
cA.setB(2.0);
double (*p)(const double);
if(true) {
p = &cA.getA; //'&' : illegal operation on bound member function expression
} else {
p = cA.getB; //'CA::getB': function call missing argument list; use '&CA::getB' to create a pointer to member
//'=' : cannot convert from 'double (__thiscall CA::* )(const double)' to 'double (__cdecl *)(const double)'
}
cA.print(p, 3.0);
So how do I get p to point to either 'getA' or 'getB' so that it is still useable by 'print'.
From what I have seen, the suggestions are to use boost or std::bind but I've had no experience with either of these. I'm hoping that I don't need to dive into these and that I'm just missing something.
Compiler MSVC++ 2008

Don't forget that a member function accepts an implicit this parameter: therefore, a member function accepting a double can't be the same thing as a non-member (free) function accepting a double.
// OK for global functions
double (*p)(const double);
// OK for member functions
double (CA:*p)(const double);
Also the way you invoke them is different. First of all, with member functions, you need an object to invoke them on (its address will eventually be bound to the this pointer in the function call). Second, you need to use the .* operator (or the ->* operator if you are performing the call through a pointer):
p = &CA::getA;
CA cA;
(cA.*p)();
Consistently, you will have to change your definition of function print():
#include <iostream>
void print(double (CA::*f)(const double), double x)
{
// Rather use the C++ I/O Library if you can...
std::cout << "Value = " << (this->*f)(x);
};
So finally, this is how you should rewrite your main() function:
int main()
{
CA cA;
cA.setA(1.0);
cA.setB(2.0);
double (CA::*p)(const double);
if (true) // Maybe use some more exciting condition :-)
{
p = &CA::getA;
}
else {
p = &CA::getB;
}
cA.print(p, 3.0);
}

Compilation Issue
This answer focuses on the compilation issue presented in the question. I would not recommend implementing this as a solution.
Pointers to member functions are best dealt with with typedefs and a macro.
Here's the macro for calling a member function:
#define CALL_MEMBER_FN(object, ptrToMember) ((object).*(ptrToMember))
Source: [33.6] How can I avoid syntax errors when calling a member function using a pointer-to-member-function?, C++ FAQ.
This saves you having to remember the ugly (object).*(ptrToMember) syntax any time you wish to call a member function by pointer.
In your class, declare a typedef called CAGetter, this will make variable declaration much simpler:
class CA
{
public:
typedef double (CA::*CAGetter)(const double x);
Then you can declare your print() function quite simply:
void print(CAGetter f, double x)
The body is also simple, clear and concise:
{
std::cout << "value = " << CALL_MEMBER_FN(*this, f)(x) << '\n';
}
Sample usage:
CA a;
a.setA(3.1);
a.setB(4.2);
// Using a variable...
CA::CAGetter p = &CA::getA;
a.print(p, 1);
// without a variable
a.print(&CA::getB, 1);
// Calling the functions from outside the class...
std::cout << "From outside (A): " << CALL_MEMBER_FN(a, p)(10) << std::endl;
std::cout << "From outside (B): " << CALL_MEMBER_FN(a, &CA::getB)(10) << std::endl;
Design Issue
Passing a pointer to a member function into a method of an instance of the same class is a design smell (you wouldn't normally pass a member variable to a method, this is no different). There is not enough information in this question to address the underlying design issue but this problem could probably be solved with separate print() methods, a member variable or with inheritance and polymorphism.

You can either use pointer to method:
class CA
{
public:
typedef double (CA::*getter)( double );
CA(void) {};
~CA(void) {};
void setA(double x) {a = x; };
void setB(double x) {b = x; };
double getA(const double x) {return x*a; };
double getB(const double x) {return x*b; };
void print(getter f, double x) {
char cTemp[256];
sprintf(cTemp, "Value = %f", (this->*f)(x));
std::cout << cTemp;
};
private:
double a, b;
};
int main()
{
CA cA;
cA.setA(1.0);
cA.setB(2.0);
CA::getter p;
if(true) {
p = &CA::getA;
} else {
p = &CA::getB;
cA.print( p, 3.0 );
}
Or use boost::bind
class CA
{
public:
typedef boost::function<double( double )> getter;
CA(void) {};
~CA(void) {};
void setA(double x) {a = x; };
void setB(double x) {b = x; };
double getA(const double x) {return x*a; };
double getB(const double x) {return x*b; };
void print(getter f, double x) {
char cTemp[256];
sprintf(cTemp, "Value = %f", f(x));
std::cout << cTemp;
};
private:
double a, b;
};
int main()
{
CA cA;
cA.setA(1.0);
cA.setB(2.0);
CA::getter p;
if(true) {
p = boost::bind( &CA::getA, &cA, _1 );
} else {
p = boost::bind( &CA::getB, &cA, _1 );
}
cA.print( p, 3.0 );
}

Related

Refactoring with AceButton Library causing "Invalid use of Non-Static member function" on compile [duplicate]

The question is the following: consider this piece of code:
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass a;
function1(&test);
function1(&aClass::aTest); // <-- How should I point to a's aClass::test function?
}
How can I use the a's aClass::test as an argument to function1? I would like to access a member of the class.
There isn't anything wrong with using function pointers. However, pointers to non-static member functions are not like normal function pointers: member functions need to be called on an object which is passed as an implicit argument to the function. The signature of your member function above is, thus
void (aClass::*)(int, int)
rather than the type you try to use
void (*)(int, int)
One approach could consist in making the member function static in which case it doesn't require any object to be called on and you can use it with the type void (*)(int, int).
If you need to access any non-static member of your class and you need to stick with function pointers, e.g., because the function is part of a C interface, your best option is to always pass a void* to your function taking function pointers and call your member through a forwarding function which obtains an object from the void* and then calls the member function.
In a proper C++ interface you might want to have a look at having your function take templated argument for function objects to use arbitrary class types. If using a templated interface is undesirable you should use something like std::function<void(int, int)>: you can create a suitably callable function object for these, e.g., using std::bind().
The type-safe approaches using a template argument for the class type or a suitable std::function<...> are preferable than using a void* interface as they remove the potential for errors due to a cast to the wrong type.
To clarify how to use a function pointer to call a member function, here is an example:
// the function using the function pointers:
void somefunction(void (*fptr)(void*, int, int), void* context) {
fptr(context, 17, 42);
}
void non_member(void*, int i0, int i1) {
std::cout << "I don't need any context! i0=" << i0 << " i1=" << i1 << "\n";
}
struct foo {
void member(int i0, int i1) {
std::cout << "member function: this=" << this << " i0=" << i0 << " i1=" << i1 << "\n";
}
};
void forwarder(void* context, int i0, int i1) {
static_cast<foo*>(context)->member(i0, i1);
}
int main() {
somefunction(&non_member, nullptr);
foo object;
somefunction(&forwarder, &object);
}
#Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:
#include <functional>
using namespace std::placeholders;
void function1(std::function<void(int, int)> fun)
{
fun(1, 1);
}
int main (int argc, const char * argv[])
{
...
aClass a;
auto fp = std::bind(&aClass::test, a, _1, _2);
function1(fp);
return 0;
}
A pointer to member function is different from a pointer to function. In order to use a member function through a pointer you need a pointer to it (obviously ) and an object to apply it to. So the appropriate version of function1 would be
void function1(void (aClass::*function)(int, int), aClass& a) {
(a.*function)(1, 1);
}
and to call it:
aClass a; // note: no parentheses; with parentheses it's a function declaration
function1(&aClass::test, a);
Since 2011, if you can change function1, do so, like this:
#include <functional>
#include <cstdio>
using namespace std;
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
template <typename Callable>
void function1(Callable f)
{
f(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d", a , b , a - b);
}
int main()
{
aClass obj;
// Free function
function1(&test);
// Bound member function
using namespace std::placeholders;
function1(std::bind(&aClass::aTest, obj, _1, _2));
// Lambda
function1([&](int a, int b) {
obj.aTest(a, b);
});
}
(live demo)
Notice also that I fixed your broken object definition (aClass a(); declares a function).
I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference
Important to note that unless you can change the signature of the code taking the function, there is no (easy) way to do this. That would be trying to implement a closure in a language that does not have closures that are the same as functions (the signature for a closure in C++ is different).
There are two actual ways to achieve this:
Use some sort of singleton/global variable that you store the closure in, and then pass a helper function that calls the needed function using that closure. Here is an example:
#include <stdio.h>
template<class C, typename ReturnType, typename... Args>
class ClosureSingleton {
typedef ReturnType (C::*FuncType)(Args...);
public:
static ClosureSingleton& getInstance() {
static ClosureSingleton instance;
return instance;
}
void setClosure(C* obj, FuncType f) {
this->obj = obj;
this->function = f;
}
static ReturnType funcPtr(Args... args) {
C* obj = getInstance().obj;
auto func = getInstance().function;
return (obj->*func)(args...);
}
private:
ClosureSingleton() {}
C* obj;
FuncType function;
public:
ClosureSingleton(ClosureSingleton const&) = delete;
void operator=(ClosureSingleton const&) = delete;
};
class aClass {
public:
void aTest1(int a, int b) { printf("%d + %d = %d\n", a, b, a + b); }
int aTest2(int a, int b) { return a + b; }
};
void function1(void (*function)(int, int)) {
function(1, 1);
}
int function2(int (*function)(int, int)) {
return function(1, 1);
}
int main() {
aClass tmp;
ClosureSingleton<aClass, void, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest1);
function1(&ClosureSingleton<aClass, void, int, int>::funcPtr);
ClosureSingleton<aClass, int, int, int>::getInstance().setClosure(
&tmp, &aClass::aTest2);
printf(
"function2: %d\n",
function2(&ClosureSingleton<aClass, int, int, int>::funcPtr));
return 0;
}
Of course, this has the obvious downside that the closure needs to be set before every call, as well as some thread safety issues. Not ideal, but potentially workable in specific circumstances
Use something like asmjit or dynamic compilation to dynamically compile and pass the function in to the C code. This will only work on machines that allow heap section to be marked as executable. It is also very much non-portable as you will be writing assembly code to accomplish this. However, if you get it working, you will indeed have a true closure, albeit a substantially higher cost to creating the closure compared to how most programming languages implement closures (they do not duplicate the function assembly, instead they use a context object)
Patch the lib/dll that has the function handler to change it's signature to allow a context object. Again, a very brittle and non optimal solution.
My original answer, which does not really answer the question, but people found it useful:
Not sure why this incredibly simple solution has been passed up:
#include <stdio.h>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
template<class C>
void function1(void (C::*function)(int, int), C& c)
{
(c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
function(1, 1);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(&test);
function1<aClass>(&aClass::aTest, a);
return 0;
}
Output:
1 - 1 = 0
1 + 1 = 2
I made the member function as static and all works:
#include <iostream>
class aClass
{
public:
static void aTest(int a, int b)
{
printf("%d + %d = %d\n", a, b, a + b);
}
};
void function1(int a,int b,void function(int, int))
{
function(a, b);
}
void test(int a,int b)
{
printf("%d - %d = %d\n", a , b , a - b);
}
int main (int argc, const char* argv[])
{
aClass a;
function1(10,12,test);
function1(10,12,a.aTest); // <-- How should I point to a's aClass::test function?
getchar();return 0;
}
If you actually don't need to use the instance a
(i.e. you can make it static like #mathengineer 's answer)
you can simply pass in a non-capture lambda. (which decay to function pointer)
#include <iostream>
class aClass
{
public:
void aTest(int a, int b)
{
printf("%d + %d = %d", a, b, a + b);
}
};
void function1(void (*function)(int, int))
{
function(1, 1);
}
int main()
{
//note: you don't need the `+`
function1(+[](int a,int b){return aClass{}.aTest(a,b);});
}
Wandbox
note: if aClass is costly to construct or has side effect, this may not be a good way.
You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.
http://cpp.sh/9jhk3
// Example program
#include <iostream>
#include <string>
using namespace std;
typedef int FooCooker_ (int);
// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
cout << "Cooking 10 Foo ..." << endl;
cout << "FooCooker:" << endl;
FooCooker (10);
}
struct Bar_ {
Bar_ (int Foo = 0) : Foo (Foo) {};
int cook (int Foo) {
cout << "This Bar got " << this->Foo << endl;
if (this->Foo >= Foo) {
this->Foo -= Foo;
cout << Foo << " cooked" << endl;
return Foo;
} else {
cout << "Can't cook " << Foo << endl;
return 0;
}
}
int Foo = 0;
};
// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* Bar1Ptr = NULL;
static int cook_in_Bar1 (int Foo) {
return Bar1Ptr->cook (Foo);
}
thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
return Bar2Ptr->cook (Foo);
}
int main () {
Bar1Ptr = new Bar_ (20);
cook_10_foo (cook_in_Bar1);
Bar2Ptr = new Bar_ (40);
cook_10_foo (cook_in_Bar2);
delete Bar1Ptr;
delete Bar2Ptr;
return 0;
}
Please comment on any issues with this approach.
Other answers fail to call existing plain C functions: http://cpp.sh/8exun

Passing a member function pointer to a non-member function within another member function

I have a code similar to the minimal example below, where the function g is provided by a library and expects double (*)(double) as an argument. I cannot change this. The example code does not compile because the member has signature double (*C::)(double) as explained in e.g. this post, with a number of possible solutions.
#include <iostream>
double g(double (*f)(double x)) { return f(0); };
class C
{
public:
C(double b) { a = b; };
double f2() { return g(&f1); };
private:
double a;
double f1(double x) { return x + a; };
};
int main()
{
C c (1);
std::cout << c.f2() << std::endl;
return 0;
}
I wonder what the best way to implement this is given that I don't want to point to C::f1 outside the class but within another member function. As far as I understand, the member function C::f1 is not static since it is only fully known after an instance of the class is initialised. Since speed is also a concern: would this be a problem with any of the possible solutions proposed elsewhere for similar versions of this issue?
Make your f1 function static:
static double f1(double x) { return x + a; };
This gives it the same signature as what your g function expects. Since a static function does not have a hidden this pointer, you will have to find some other way to get the value of a into it.
Okay, based on the comments and ideas from the post mentioned before, I will suggest to change g as follows and add a wrapper function f2_wrapper.
#include <iostream>
double g(double (*f)(double x, void *context), void *context)
{
return f(0, context);
};
class C
{
public:
C(double b) { a = b; };
double f1(double x) { return x + a; };
double f2();
private:
double a;
};
double f2_wrapper(double x, void* context)
{
C *c = (C*) context;
return c->f1(x);
}
double C::f2() { return g(&f2_wrapper, this); }
int main()
{
C c (1);
std::cout << c.f2() << std::endl;
return 0;
}

Get reference to member function overloaded by const specification

Here is some class with two overloaded methods foo:
class Object {
public:
Object (double someVal) : val(someVal) { }
double getter () const { return val; }
double& getter () { return val; }
private:
double val;
};
So now the double Object::getter() const function will be called on const instances
const Object instance(42);
cout << instance.getter() << endl; // called: `double getter() const`
Now, I am trying to get reference to double getter() const function and assign it to std::function type
const Object instance(42);
function<double(const Object&)> foo = &Object::getter;
cout << foo(instance) << endl;
The code works fine if function double& getter() is removed, but with it I got the following error on the second line:
test.cpp:18:34: error: no viable conversion from '<overloaded function type>' to
'function<double (const Object &)>'
function<double(const Object&)> foo = &Object::getter;
^ ~~~~~~~~~~~~~~~
It seems that error happens, because system tries to call double& getter().
The question is how to force calling of double getter() const?
The full listing is attached here
By casting to the specific function pointer type:
std::function<double(const Object&)> foo = static_cast<double(Object::*)() const>(&Object::getter);
Just use a lambda closure:
Object o{0.0};
std::function<double()> f = [o](){ return o.getter(); };
The lambda calls the const version of getter(), as captured variables are const by default (otherwise you'd have to use mutable).
Address of Overload functions defined 7 contexts where the correct overload can be deduced. Yet std::function<...> is not one of them. Thus, the overload function to get address of is ambiguous.
There are a few ways to select the overload you want:
const Object instance(42);
// Use static_cast to select overload
std::function<double(const Object&)> foo = static_cast<double(Object::*)() const>(&Object::getter);
// Use lambda to select overload
// std::function type parameters can be omitted since c++ 17
// Guaranteed copy elision since c++ 17
std::function bar = [](const Object& instance) { return instance.getter(); };
// Use std::mem_fn
std::function<double(const Object&)> mfn = std::mem_fn<double() const>(&Object::getter);
However, an idiomatic way to declare methods with similar functionality but differed by constness is actually to declare two different functions: foo() and cfoo(). Think about begin() and cbegin(). The latter returns a const iterator.
You can use a typedef to disambiguate the function you want:
#include <iostream>
#include <functional>
class Object {
public:
Object (double someVal) : val(someVal) { }
double getter () const { return val; }
double& getter () { return val; }
private:
double val;
};
typedef double (Object::*funtype)() const;
int main()
{
const Object instance(42);
std::function<double(const Object&)> foo = static_cast<funtype>(&Object::getter);
std::cout << foo(instance) << std::endl;
}
run on cpp.sh
Or, without casting:
#include <iostream>
#include <functional>
class Object {
public:
Object (double someVal) : val(someVal) { }
double getter () const { return val; }
double& getter () { return val; }
private:
double val;
};
typedef double (Object::*funtype)() const;
int main()
{
const Object instance(42);
funtype temp = &Object::getter;
std::function<double(const Object&)> foo = temp;
std::cout << foo(instance) << std::endl;
}
run on cpp.sh
Yet another example, going through some options.
// auto mem_fn = static_cast<double (Object::*)() const>(&Object::getter);
// or shorter:
double (Object::*mem_fn)() const = &Object::getter;
// store member function (without instance)
std::function<double(const Object&)> foo = mem_fn;
std::cout << foo(instance) << "\n";
// bind with instance
auto bound = std::bind(mem_fn, &instance);
std::cout << bound() << "\n";
// store member function (with instance)
std::function<double()> bar = bound;
std::cout << bar() << "\n";
// store member function (with instance), without the intermediate steps
std::function<double()> baz =
std::bind(
static_cast<double (Object::*)() const>(&Object::getter),
instance
);
std::cout << baz() << "\n";

Do not use class member function inside class

I want to write an object-oriented wrapper around old C-style functions, while keeping the actual function names the same. Take a look at an example:
#include <iostream>
void doStuff(int a, float b)
{
std::cout << "a = " << a << ", b = " << b << "\n";
}
class Stuff
{
private:
int a;
float b;
public:
Stuff(int newA, float newB) : a(newA), b(newB) { }
int getA() { return a; }
float getB() { return b; }
};
class Widget
{
public:
void doStuff(Stuff s)
{
doStuff(s.getA(), s.getB()); //error: no matching function for call to 'Widget::doStuff(int, float)'
}
};
int main()
{
Widget w;
w.doStuff(Stuff(42, 3.14f));
return 0;
}
In this example, void doStuff(int a, float b) is the old C-function. Because in my real code, its equivalent is in an external library/header file, I cannot change its name. Next, Stuff is a container for keeping the values void doStuff(int a, float b) needs. The important things happen in Widget: void Widget::doStuff(Stuff s) should be the actual wrapper. I now expect doStuff(s.getA(), s.getB()) to call the old C-style function void doStuff(int a, int b) but the compilation fails with the given error.
Is it possible to make this code work without changing the name of the both doStuff functions? One option I already thought of is surrounding void doStuff(int a, float b) by some namespace. This works, but seems like very bad practice to me.
My compiler is mingw-w64 with g++ 5.2.0, so C++11 and C++14 are available.
The doStuff(Stuff s) method in your class hides the global function doStuff(int a, float b). If you want to call the global doStuff function, you have to use the scope resolution operator :: (::doStuff(s.getA(), s.getB());)
Try making your call like this:
::doStuff(s.getA(), s.getB());

C++ Passing pointer to non-static member function

Hi everyone :) I have a problem with function pointers
My 'callback' function arguments are:
1) a function like this: int(*fx)(int,int)
2) an int variable: int a
3) another int: int b
Well, the problem is that the function I want to pass to 'callback' is a non-static function member :( and there are lots of problems
If someone smarter than me have some time to spent, he can look my code :)
#include <iostream>
using namespace std;
class A{
private:
int x;
public:
A(int elem){
x = elem;
}
static int add(int a, int b){
return a + b;
}
int sub(int a, int b){
return x - (a + b);
}
};
void callback( int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
int main()
{
A obj(5);
//PASSING A POINTER TO A STATIC MEMBER FUNCTION -- WORKS!!
// output = 'Value of the callback: 30'
callback(A::add, 10, 20);
//USING A POINTER TO A NON-STATIC MEMBER FUNCTION -- WORKS!!
int(A::*function1)(int, int) = &A::sub;
// output = 'Non static member: 3'
cout << "Non static member: " << (obj.*function1)(1, 1) << endl;
//PASSING A POINTER TO A NON-STATIC MEMBER FUNCTION -- aargh
// fallita! tutto quello sotto non funziona --> usa i funtori???
// puoi creare una classe wrapper ma non riuscirai mai a chiamare da callback
int(A::*function2)(int, int) = &A::sub;
int(*function3)(int, int) = obj.*function2; //[error] invalid use of non-static member function
callback(function3, 1, 1);
}
There's a way to create my pointer in the way I tried to wrote, like int(*fx)(int, int) = something? I searched a lot but no-one could gave me an answer (well, there was an answer: "NO", but I still think I can do something)
I heard also about functors, may them help me in this case?
Thanks to anyone
PS: sorry for my bad english
EDIT1:
I can use something like this:
template <class T>
void callback2( T* obj, int(T::*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << (obj->*fx)(a, b) << endl;
}
void callback2( void* nullpointer, int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
and in my main:
callback2(NULL, &mul, 5, 3); // generic function, it's like: int mul(int a, int b){return a*b;}
callback2(NULL, &A::add, 5, 3); //static member function
callback2(&obj, &A::sub, 1, 1); //non static member function
I'm not completely sadisfied, because I don't want to pass my 'callback2' the first parameter (the object)...
The question, for people that didn't understand my (bad) explanation, is: can I delete the first parameter in my callback2 function?
the prototype will be
void callback2(int(*fx)(int, int), int a, int b)<br>
and I will call like this:
callback2(&obj.sub, 1, 3);
Functions cannot be referenced this way:
int (*function3)(int, int) = obj.*function2;
You have to pass the address of the function like this:
int (*function3)(int, int) = std::mem_fn(&A::sub, obj);
// ^^^^^^^^^^^^^^^^^^^^^^^^^
The expression function2 decays into a pointer-to-function which allows it to work.
I would do it with std functors, here is a simple example based off of your code:
#include <iostream>
#include <functional>
using namespace std;
class A{
private:
int x;
public:
A(int elem){
x = elem;
}
static int add(int a, int b){
return a + b;
}
int sub(int a, int b) const{
return x - (a + b);
}
};
void callback( std::function<int(const A& ,int,int )> fx, A obj, int a, int b)
{
cout << "Value of the callback: " << fx( obj, a, b) << endl;
}
int main()
{
A obj(5);
std::function<int(const A& ,int,int )> Aprinter= &A::sub;
callback(Aprinter,obj,1,2);
}