Reputation: 59
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.
Upvotes: 1
Views: 618
Reputation: 33
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);
}
}
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 or std::bind
.
Upvotes: 1