I wanted to have an abstraction between two classes and need to pass data between them, at the interface level we are not aware of the type of data, but the concreate implementation of the interfaces are aware of the data type, and they are different for each concreate implementation. below is the example:
class IA
{
void func(uint8_t datatype,void* arg) = 0;
};
class IB
{
void doSomethingOne() = 0;
void doSomethingTwo() = 0;
private:
IA* pA;
};
typedef enum color{RED,BLUE,GREEN} ColorType;
typedef enum shape{CIRCLE,SQUARE,RECTANGLE} ShapeType;
class DerivedB :public IB
{
Derived(DerivedA* p):pA(p)
{}
void doSomethingOne()
{
//do
//do
ColorType color = RED;
RedData* pRedData = {}; //some structure that has data
pA->func(static_cast<uint8_t>(color),pRedData);
}
void doSomethingTwo()
{
//do
//do
ColorType color = BLUE;
BlueData* pBlueData = {}; //some structure that has data
pA->func(static_cast<uint8_t>(color),pBlueData);
}
};
class DerivedTwoB :public IB
{
DerivedTwoB(DerivedATwo * p):pA(p)
{}
void doSomethingOne()
{
//do
//do
ShapeType shape = CIRCLE;
CircleData* pData = {}; //some structure that has data
pA->func(static_cast<uint8_t>(shape),pData );
}
void doSomethingTwo()
{
//do
//do
ShapeType shape = SQUARE;
SquareData* pData = {}; //some structure that has data
pA->func(static_cast<uint8_t>(shape),pData );
}
};
class DerivedA : public IA
{
void func(colorType color,void* arg)
{
if(color == RED)
{
RedData pData* = nullptr;
pData = reinterpret_cast<RedData*>(arg);
//use pData
.
.
//do something with pData
}
if(color == BLUE)
{
BlueData pData* = nullptr;
pData = reinterpret_cast<BlueData*>(arg);
//use pData
.
.
//do something with pData
}
}
};
class DerivedATwo : public IA
{
void func(ShapeType shape,void* arg)
{
if(shape == CIRCLE)
{
CircleData pData* = nullptr;
pData = reinterpret_cast<CircleData*>(arg);
//use pData
.
.
//do something with pData
}
if(shape == SQUARE)
{
SquareData pData* = nullptr;
pData = reinterpret_cast<SquareData*>(arg);
//use pData
.
.
//do something with pData
}
}
};
I want to avoid passing void* data across objects, but this would lead to implementation of several func() for each data type. and breaks the implementation for interfaces (Substitution Principle). Can I achieve the same behavior using other methods but avoid using void* and achieve type safety?
void*
is the ultimate type erasure. But it's also not very type safe. Templates can help you out here depending on what you're actually trying to achieve. Failing that, even an interface might be better in some cases. Ultimately it comes down to what you're doing and what your constraints are. – AndyG Oct 21 '20 at 18:57void *
can be the right answer, usually it's not. – user4581301 Oct 21 '20 at 19:20