heltena wrote:
Hi,
I have this "interface" (abstract class):
[...] and the question:
I have a lot of functions (more that two) in the callback interface,
can I use macros or templates to make more easy the new functions
implementation?
Based on your requirement, I think you can consider each function as
one object.
all callback functions will derive from base class. Manager class will
easy to manage them. If you want to add a new function, you only derive
the base class to implement the function. It may be one solution shown
in the following code:
======= TEST CASE =============== ==
#include <iostream>
#include <list>
using namespace std;
class Callback
{
public:
Callback() {}
virtual ~Callback() {}
virtual void function()=0;
//...
};
class Function1 : public Callback
{
public:
Function1(){}
virtual void function() { cout << "Function1: no argument" <<
endl; }
//....
};
class Function2: public Callback
{
private:
string value;
public:
Function2(const string &v): value(v) {}
virtual void function() { cout << "Function2: string value=" <<
value << endl; }
//....
};
class Function3: public Callback
{
private:
int value;
public:
Function3(int v): value(v) { }
virtual void function() { cout << "Function3: int value" << value
<< endl; }
//....
};
class Function4: public Callback
{
private:
int value;
public:
Function4(int v): value(v) { }
virtual void function() { cout << "Function4: int value" << value
<< endl; }
//....
};
// more functions ....
class Manager
{
private:
list<Callback *> m_callbacks; // it contains correct pointers
public:
void insert_callback s(Callback * new_func) {
m_callbacks.pus h_front(new_fun c); }
void destroy_callbac ks(void);
void call_function() ;
Manager() {}
~Manager() { destroy_callbac ks( ); }
//.....
};
void Manager::call_f unction()
{
list<Callback *>::iterator it = m_callbacks.beg in(),
end = m_callbacks.end ();
while (it != end)
{
(*it)->function();
it++;
}
}
void Manager::destro y_callbacks()
{
list<Callback *>::iterator it = m_callbacks.beg in(),
end = m_callbacks.end ();
while (it != end )
{
delete (*it);
it++;
}
}
int main()
{
Manager *manager = new Manager();
Callback *f1 = new Function1();
manager->insert_callbac ks(f1);
string s = "Hello world! ";
Callback *f2 = new Function2(s);
manager->insert_callbac ks(f2);
Callback *f3 = new Function3(333);
manager->insert_callbac ks(f3);
Callback *f4 = new Function4(444);
manager->insert_callbac ks(f4);
// call function
manager->call_function( );
return 0;
}
==== output ===
Function4: int value444
Function3: int value333
Function2: string value=Hello world!
Function1: no argument