solod91
1
Hello, I want to use callback function in my class, but I don’t know how.
Example:
Class myClass
{
myClass( /*here I want to pass callback func arg */)
{ _callBackFunc = /* arg */ }
/* type */ _callBackFunc;
void func() { /* here I want to call _callBackFunc */ }
}
What type is callback func?
How to call it?
Ps: sorry for my English. Thank you.
You can use std::function:
class myClass{
std::function<void()> callback;
void func(){
callback();
};
}
to set callback use std::bind
callback = std::bind(&SomeClass::someFunction, someClassInstance);
almax27
3
When calling an std::function it is recommended to test it is valid:
if(callback) { callback(); }
(std::function implements operator bool so we don’t need an explicit comparison)
You can also use lambda’s inline to implement functions:
auto function = [=]()
{
printf("I'm a function!");
};
Further reading:
http://en.cppreference.com/w/cpp/utility/functional/function
http://en.cppreference.com/w/cpp/language/lambda