4

I am trying to initialize a struct with a function pointer, however I am having trouble doing so unless it is done with a global function. The following code works:

float tester(float v){
    return 2.0f*v;
}

struct MyClass::Example{
    typedef float(*MyFunc)(float);

    MyFunc NameOfFunc;

    float DoSomething(float a){
        return NameOfFunc(a);
    }
};

struct Example e;
e.MyFunc = tester;

My problem is whenever I try to do this with the tester function as a function in MyClass the code no longer works. In other words, I change the tester function to:

float MyClass::tester(float v){
    return 2.0f*v;
} 

Any and all help is appreciated (including links)! I have tried googling around for the problem but am unsure what to search (I've tried things such as "C++ struct function pointer initialization in class" to no avail)

2
  • 2
    You need "c++ pointer to member function". BTW, member function requires context (object to be this), so it can't be used the same way as plain functions. Commented Dec 16, 2013 at 23:35
  • Since MyClass::tester doesn't seem to depend on any non-static members of MyClass, maybe you want it to be static or just a free function as you had before? (and then this code would work) Commented Dec 16, 2013 at 23:37

2 Answers 2

4

This is because when you put the function as a member of the class, it will no longer be of the type float (*)(float), but rather, float (MyClass::*)(float).

Look into std::function and std::mem_fn to solve these problems.

Example:

struct foo {
    float bar(int x, int y) {}
};

// This works
std::function<float(int, int)> func = std::mem_fn(&foo::bar);
Sign up to request clarification or add additional context in comments.

1 Comment

I have tried doing what you have suggested to some degree, but have posted a follow up question as this led to more problems
2

If you want NameOfFunc to point to float MyClass::tester(float v) then the Myfunc declaration must be,

typedef float (MyClass::*MyFunc)(float);

But then it cannot point to float tester(float v) I don't think you can have one type that can point to either.

Also shouldn't e.MyFunc = tester; be e.NameOfFunc = tester;?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.