Joe said:
Tom,
What's unclear?
I have an ID passed to a method of a class, say class1.
That function then creates one of several classes derived from another base
class depending on the ID.
Whatever one is created I want to perform an overloaded function of class1,
the overloading depending on which derived class was created. Each does
something very similar (kicks off a thread) but a different derived thread
class with a different parameter set - the parameter sets are themselves
classes and have a different lifetime to thread classes (I access them after
the thread has died).
As well as just wondering wether it can be done I wanded to avoid a big
switch or if-else.
In the extreme say ther were dozens of slightly different classes, it would
be nice just to avoid any conditional statements and just have C++ do it
implicitely if possible.
Anything other info you need just say.
You need to implement the Factory Design Pattern. Search this newsgroup
for "factory".
Here is how I have implemented the factory:
1. Each class has a parent class. The factory returns a pointer to
a dynamically created child.
2. Each child has a static "create" class that returns a pointer to
a dynamically allocated child:
class Child1
: public Parent
{
public:
static Parent * create(ID_TYPE id);
};
Parent *
Child1 ::
create(ID_TYPE id)
{
if (id == CHILD1_ID)
{
return new Child1;
}
else
return NULL;
}
3. The Factory has a table of pointers to create functions for each
child class. Each function is executed by dereferencing the
pointer (and passing the ID). If the pointer is null, the next
function is executed.
In your case, you could have a virtual method in the parent class
for launching threads (or lets us call it initializing). The factory
could execute this method after successful creation of the child:
if (pointer_to_child)
{
pointer_to_child->Initialize();
// or pointer_to_child->Create_Thread();
}
Alternatives:
1. Create a table of <id, pointer to create function> and use
the std::lower_bound to find the appropriate function pointer.
For small quantities, the above method is faster than using
the binary_search.
2. Have the create() function start the thread for that child,
rather than the factory.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book