Usa std::function
and lambdas (or std::bind()
) per memorizzare oggetti chiamabili:
#include <functional>
#include <iostream>
class Test
{
public:
void blah() { std::cout << "BLAH!" << std::endl; }
};
class Bim
{
public:
void operator()(){ std::cout << "BIM!" << std::endl; }
};
void boum() { std::cout << "BOUM!" << std::endl; }
int main()
{
// store the member function of an object:
Test test;
std::function< void() > callback = std::bind(&Test::blah, test);
callback();
// store a callable object (by copy)
callback = Bim{};
callback();
// store the address of a static function
callback = &boum;
callback();
// store a copy of a lambda (that is a callable object)
callback = [&]{ test.blah(); }; // often clearer -and not more expensive- than std::bind()
callback();
}
Risultato:
BLAH!
BIM!
BOUM!
BLAH!
compila e gestita: http://ideone.com/T6wVp
std::function
può essere utilizzato come un qualsiasi oggetto copyiable, quindi sentitevi liberi di memorizzare da qualche parte come un callback, come negli Stati dell'oggetto. Significa anche che puoi metterlo liberamente in contenitori standard, come std::vector< std::function< void() > >
.
Si noti inoltre che equivale boost::function and boost::bind sono stati disponibili per anni.
"Inoltre, non è templato che si sente come ho potuto fare di più" Il codice C++ non deve essere configurato come C++. –
@NicolBolas ad essere onesti questa soluzione ha fatto utilizzare un unico e funziona * davvero * bene (lambda) –