I have several datacontainertype like this but they differ in their content:
struct containerRequest
{
uint8_t data1
uint8_t data2
};
struct containerResponse
{
uint8_t data1;
uint8_t data2;
};
union myType
{
containerRequest Request;
containerResponse Response;
};
Now I would like to create an abstract interface to ensure all of this interfaces have an MyDatatype like this
class IMyInterface
{
public:
union myType
{
X Request;
Y Response;
};
bool IsMyType(myType& data) = 0;
void DoThings(myType& data) = 0;
};
I thought of using template but this brakes the rest of my code:
template <typename X, typename Y>
class IMyInterface
{
...
}
but this breaks the rest of my code.
Because I have a collection of the different containers:
void addContainer(IMyInterface& data)
{
collection.push_back(&data);
}
when I use Templates in the interface g++ forces me to specify the types of my templates.
How can I define X and Y in my derived class without the need to specific the type in my collection?
Sounds like you need (runtime) polymorphism, i.e. want code which deals with an
IMyInterfacewithout knowing it’s precise type. Templates alone won’t get you there, since they only provide compile-time polymorphism. The parts of C++ which provide what you want are RTTI (run-time type information) and virtual functions. One of the extremely powerfull features of C++ is that you can combine the two approaches. In your case, that means turningIMyInterfaceinto a template, but letting that template inherit from a non-templated base class which defines the virtual functions you need. Here’s an example.In real code, you should of course not store raw points in the
interfacesvector, but instead use some kind of smart pointer.boost::shared_ptr(orstd::shared_ptrif you’re using C++11) would be a good choice. You might also want to take a look atboost::any, which wraps objects of arbitrary type and a safe manner (i.e., in a way, it’svoid*done right).Your use of
unionis a bit dubious, btw. How would aDoThingsmethod know whether the data contains a request or a response? You might want to consider usingboost::variantinstead of a C-style union.