that looks like very good for me ...
only one thing is missing ... boost :)
S.
On 12 Apr, 14:12, timor.su...@gmail.com wrote:
Hi group,
I would like to simulate something that can be quite similar to
"Events".
I would like that a member function of a class can be "setted" as an
Eventand that this method can be called after something special.
Consider the following example :
I'm setting a function with a pointor function, then in a while-true
block, I ask for an input, if input is "abc", i'm firing anevent
(that prints "abc").
#include <iostream>
#include <string>
.>
using namespace std;
typedef void (*fPtrEvent)();
classEvent
{
private:
static fPtrEvent fEvent;
public:
Event() {};
static void Set(fPtrEvent f)
{
fEvent = f;
}
void WhileTrue()
{
while(1)
{
string s;
cin >> s;
if (s == "abc" && fEvent != 0)
fEvent();
if (s == "q")
break;
}
}
};
fPtrEventEvent::fEvent = 0;
class Test
{
public:
static void DoPrint()
{
cout << "print abc" << endl;
}
};
int main (void)
{
Event*c = newEvent();
c->Set(&Test::DoPrint);
c->WhileTrue();
delete c;
return 0;
}
for more general solution check boost::signals library
it is a type safe callback library
you can also check battle tested libsigc++
which does the same think in almost the
same way as boost::signals
#include <iostream>
#include <string>
#include <boost/signals.hpp>
#include <boost/bind.hpp>
(you spend most of your time designing
your program, typing five extra characters
should not be such a chore. Injecting whole
of std into your namespace is never a good
idea)
//using namespace std;
classEvent
{
::boost::signal<void()> sig_;
public:
template<class Fun>
::boost::signals::connection connect(Fun fun)
{
return sig_.connect(fun);
}
void WhileTrue()
{
std::string s;
do
{
std::cin >> s;
if (s == "abc")
// call all connected
sig_();
}while(s != "q");
}
};
class Test
{
public:
void DoPrint()
{
std::cout << "Test\n";
}
};
void Test1()
{
std::cout << "Test1\n";
}
int main()
{
Eventc;
Test t;
// connect non static member function
c.connect(boost::bind(&Test::DoPrint, &t));
// connect non member function
c.connect(&Test1);
c.WhileTrue();
return 0;
}- Masquer le texte des messages pr=E9c=E9dents -
- Afficher le texte des messages pr=E9c=E9dents -- Masquer le texte des m=