Skip to content

Instantly share code, notes, and snippets.

@bfueldner
Created October 8, 2015 22:05
Show Gist options
  • Save bfueldner/d9c284b9da925fb7e0e0 to your computer and use it in GitHub Desktop.
Save bfueldner/d9c284b9da925fb7e0e0 to your computer and use it in GitHub Desktop.
Callback with C++ class
#include <iostream>
#include <vector>
struct callback_interface
{
virtual void callback() = 0;
};
typedef std::pair<callback_interface *, int> callback_timeout;
std::vector<callback_interface*> callbacks;
std::vector<callback_timeout> callbacks_timeout;
struct classA
{
struct callback_private:
callback_interface
{
classA *owner;
callback_private(classA *owner):
owner(owner)
{
}
void callback()
{
owner->callback();
}
};
callback_private cb;
int i;
classA(int i):
cb(this),
i(i)
{
callbacks_timeout.push_back(std::make_pair(&cb, 1000));
}
void callback()
{
std::cout << i << std::endl;
}
};
struct classB
{
struct callback_private:
callback_interface
{
classB *owner;
callback_private(classB *owner):
owner(owner)
{
}
void callback()
{
owner->callme();
}
};
callback_private cb;
float f;
classB(float f):
cb(this),
f(f)
{
callbacks_timeout.push_back(callback_timeout(&cb, 100));
}
void callme()
{
std::cout << f << std::endl;
}
};
int main(int argc, char *argv[])
{
classA a(1), b(4);
classB c(2.5), d(7.3);
for (const callback_timeout &call_time: callbacks_timeout)
{
std::cout << call_time.second << std::endl;
call_time.first->callback();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment