Reputation: 5642
I am having trouble compiling the following code. I am usually OK with using callback functions, but it seems that when using a member function, it has issues. Do you know what is the problem with my declaration/definition of the parameter startPlayback?
class VmapPlayer
{
void startPlayback();
void playAdBreak(int a, void (*callback)());
};
void VmapPlayer::playAdBreak(int a, void (*callback)())
{
cout << a << endl;
//callback();
}
void VmapPlayer::startPlayback()
{
playAdBreak(5, startPlayback); // Compile issue with "startPlayback" parameter
}
Upvotes: 0
Views: 86
Reputation: 212
void (*callback)() declares callback as a function pointer, but startPlayback is not a free function, but a member function. This is one way to fix it:
class VmapPlayer
{
void startPlayback();
void playAdBreak(int a, void (VmapPlayer::*callback)());
};
void VmapPlayer::playAdBreak(int a, void (VmapPlayer::*callback)())
{
cout << a << endl;
(this->*callback)();
}
void VmapPlayer::startPlayback()
{
playAdBreak(5, &VmapPlayer::startPlayback);
}
If you need more flexibility, and C++11 is available, you could use std::function<void()>
to hold your callback, and fill it with a lambda expression, like [this](){ startPlayback(); }
Upvotes: 1