Cheshire Cat
Cheshire Cat

Reputation: 233

Pointer to class member function as an argument to external function

I'm trying to implement some class methods to OpenGL libraries but I have troubles with pointers to functions. Anyway, let's say we have C++ code:

int funct1(int x){
    return x*x;
}
class foo{
public:
    int funct2(int x){
        return x*x;
    }
};
int conv(int (*f)(int)){
    return f(1);
}
int main(){
    conv(funct1);
    foo bar;
    conv(funct2);
}

I do realise that funct2 is internal method of foo class, but trying to change conv(funct2) to something like conv(bar.funct2) gives error like:

argument of type ‘int (foo::)(int)’ does not match ‘int (*)(int)’

I was trying to find help in other posts like that - but always it was very complicated. Can someone post here changed and working code here?

Upvotes: 2

Views: 1061

Answers (3)

Cheshire Cat
Cheshire Cat

Reputation: 233

I found nice way to solve this problem:

class MyClass;
static MyClass* ptr;
class MyClass{
void Func(){something;}
static void Func2(){ptr->Func();}
void RunFunc(){
ptr=this;
RunningExternalFunction(Func2);
}
};

Voila!

Upvotes: 0

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

declare funct2 as static

int funct1(int x){
return x*x;
}
class foo{
public:
static int funct2(int x){
return x*x;
}
};
int conv(int (*f)(int)){
return f(1);
}
int main(){
conv(funct1);
foo bar;
conv(foo::funct2);
}

Upvotes: 1

Nicolas Holthaus
Nicolas Holthaus

Reputation: 8273

If your compiler supports c++11 you can do the following:

#include<functional>

int funct1(int x){
    return x*x;
}
class foo{
public:
    int funct2(int x){
        return x*x;
    }
};

int conv(int (*f)(int)){
    return f(1);
}

int main(){
    conv(funct1);
    foo bar;
    auto boundFunct2 = std::function<int(int)>(std::bind(&foo::funct2,bar,std::placeholders::_1));
    conv(boundFunct2.target<int(int)>());
}

Basically, you're binding funct2 to an instance of the class, namely bar, then creating a function object back out of that. In order for it to make the signature expected by conv(), you call the target member on the function object.

The nice thing is you don't have to change any of the functions or classes, which I'm assuming you can't as they're probably openGL library objects.

Upvotes: 0

Related Questions