I would like to replace big switch with something more elegant.
class Base
{
public:
Base(void*data, int size);
virtual void Something() = 0;
}
class A : public Base
{
public:
A(void*data, int size) : Base(data, size) {}
void Something() override;
}
class B : public Base
{
public:
B(void*data, int size) : Base(data, size) {}
void Something() override;
}
...
{
char c = input;
switch (c)
{
case 'a':
{
A obj(data, size);
obj.Something();
break;
}
case 'b':
{
B obj(data, size);
obj.Something();
break;
}
...
}
}
as you see in the example class A
and B
do not differ from outside.
I would like to find a way to eliminate that switch that just instantiate correct class and call same method on it, in my real code that switch is over 1000 lines long, and there is much more classes, but I can not find any way to get rid of it.
In real code I have 2 enums instead of char, and there are more switches, but I hope problem is clear.
One of my ideas was use templates on base class, but I did not find a way how to instantiate correct child without that huge switch.
EDIT
I receive packet from network and want to parse it and handle it. These classes a, b, ...
do not have any private or public members, base class have only raw pointer to date, and shared pointer to response socket (also from constructor).
I would like the compiler to generate that switch for me with templates? or some other mechanic to remove that repetitive source code. Right now it is still in testing phase, but it handle around 1000 packets per second, so I do not want to remove switch and lose performance, on allocation and deallocation on the heap.