简体   繁体   中英

How to assign a struct function pointer to a struct function

I have a struct Game with a function pointer called onBegin

struct Game {
  // ...
  void (*onBegin)(Game&);
  // ...
};

What I am attempting to do is allow the user to create their own onBegin function, in which they could say

void CustomFunc(Game& g) {
  // Do something
}

Game g = Game();
g.onBegin = *CustomFunc;

What I am attempting to do is make a function and then set the pointer onBegin to point at that default function.

struct Game {
public:
  void (*onBegin)(Game&);
private:
  void defualtOnBegin(Game&);
};

// In the constructor
Game::Game() {
  // ...
  this->onBegin = this->defaultOnBegin; // This is what is giving me the error
}

I receive the error: a pointer to a bound function may only be used to call the function and do not know what is wrong here.

What I am attempting to do is allow the user to create their own onBegin function...

You could achieve that in different ways, however as you want to go for a function-pointer approach, you might want to utilize std::function like:

#include <iostream>
#include <functional>

struct Game {
    public:
        Game(std::function<void(Game&)> customOnBeginFnc = nullptr) {
            if(customOnBeginFnc) {
                customOnBeginFnc(*this);
            } else {
                defaultOnBegin(*this);
            }
        }

    private:
        void defaultOnBegin(Game&) {
            std::cout << "Default 'onBegin'\n";
        }
};

void customOnBegin(Game&) {
    std::cout << "Custom 'onBegin'\n";
}

int main() {

    {
        std::cout << "Starting a 'default' game...\n";
        Game g;
    }

    {
        std::cout << "Starting a 'customized' game...\n";
        Game g(customOnBegin);
    }
}

Run it here.

The advantage of that approach would be that you are not limited to free functions but you could also bind a member function to it via a lambda orstd::bind .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM