'Emulating Polymorphism without virtual pointers/overhead
Before reading I must emphasise I have demanding performance requirements (not premature optimization- processing millions of messages and need to design with performance in mind from the beginning). If I didn't have these requirements I would just use polymorphism.
I am using C++17 and have ~30 different classes/types. Each class uses CRTP to inherit from a Base and has three identical methods:
template<class D>
struct Base
{
// Shared behaviour
}
struct ObjectN : public Base<ObjectN>
{
void doA(int p);
void doB(int p);
void doC(int p);
};
Because I am avoiding Polymorphism I just declare the 30 types manually:
Object1 _object1;
.
.
Object30 _object30;
Currently I have 3 wrapper methods to invoke the 3 methods across the 30 classes, switching on the object type and invoking the relevant object's method (doA()
, doB()
or doC()
):
void callDoA(int object_type)
{
switch(object_type)
{
case Object1:
_object1.doA();
break;
case Object2:
_object2.doA();
.
.
case Object30:
_object30.doA();
}
}
void callDoB(int object_type)
{
switch(object_type)
{
case Object1:
_object1.doB();
break;
case Object2:
_object2.doB();
.
.
case Object30:
_object30.doB();
}
}
void callDoC(int object_type)
{
switch(object_type)
{
case Object1:
_object1.doC();
break;
case Object2:
_object2.doC();
.
.
case Object30:
_object30.doC();
}
}
With 30 x 3 case labels this is not good. The design doesn't feel right.
Given the switch statements are effectively identical (except the method called) is there a smarter way I could do this? I was thinking of re-using the switch statement and passing something in? My first though was a lambda but I'm concerned about performance. However, I can't have 90 case labels!
I could put the 30 types within a variant if helps provide a solution?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|