Eldhom
Eldhom

Reputation: 33

Function pointer to class method

I need some help with using a function pointer to another class method in a class but I'm not sure how to make it able to call any class method.

The code is probably very wrong and that's because I'm pretty confused by how it works, but hopefully this code snipped will explain what I want to be able to do.

#ifndef BUTTON_INPUT_HPP
#define BUTTON_INPUT_HPP

#include"../InputComponent.hpp"

class ButtonInput : public InputComponent {
public:
    template<typename C>
                            ButtonInput(void(C::*f)(), C* object);
    virtual void            update(World& world, GraphicsComponent& graphics, Actor& actor);
private:
    void (C::*func)();
};

#endif

The update function checks if the button is clicked, and should call func() if it is.

Upvotes: 3

Views: 146

Answers (1)

Felix Glas
Felix Glas

Reputation: 15524

Here's a simple example of how to store a function pointer to a member function along with a pointer to an instance. The stored function can later be called using call().

#include <iostream>

template<typename C>
class FuncHolder {
public:
    FuncHolder(void (C::*f)(), C* object) : func(f), c(object) {}
    void call() { (c->*func)(); } // Make the call.
private:
    void (C::*func)(); // Pointer to member function.
    C* c;              // Pointer to object.
};

// Example class with member function.
struct Foo {
    void test() { std::cout << "Foo" << std::endl; }
};

int main() {
    Foo foo;
    FuncHolder<Foo> f(&Foo::test, &foo);

    f.call();
}

Upvotes: 1

Related Questions