In the following code, I've got an interface called IDecoder
which should be implemented by any decoder class (DecoderA
and DecoderB
here). IDecoder
has a bitset<>
in it, therefore I've made IDecoder
a template class and the size of bitset
is determined in the derived classes. I've also got a Container
class which should hold a pointer to the IDecoder
class, but since IDecoder
is not a complete type, I've added a dummy DecoderBase
class from which IDecoder
inherits:
#include <iostream>
#include <bitset>
class DecoderBase
{
public:
DecoderBase(){}
virtual ~DecoderBase(){}
};
template<size_t nb>
class IDecoder : public DecoderBase
{
public:
IDecoder(){}
virtual ~IDecoder(){}
virtual std::bitset<nb> GetDecodedFields() = 0;
};
const int DecoderAMaxFields = 100;
const int DecoderBMaxFields = 200;
class DecoderA : public IDecoder<DecoderAMaxFields>
{
public:
DecoderA(){}
~DecoderA(){}
std::bitset<DecoderAMaxFields> GetDecodedFields()
{
std::bitset<DecoderAMaxFields> bits;
// assume we've decoded fileds number 1 and 10 here
bits[1] = 1;
bits[10] = 1;
return bits;
}
};
class DecoderB : public IDecoder<DecoderBMaxFields>
{
public:
DecoderB(){}
~DecoderB(){}
std::bitset<DecoderBMaxFields> GetDecodedFields()
{
std::bitset<DecoderBMaxFields> bits;
// assume we've decoded fileds number 11, 29, 110 & 142 here
bits[11] = 1;
bits[29] = 1;
bits[110] = 1;
bits[142] = 1;
return bits;
}
};
class Container
{
public:
Container(){}
virtual ~Container(){}
void SetDecoder(DecoderBase* decoder)
{
mDecoder = decoder;
}
DecoderBase* GetDecoder()
{
return mDecoder;
}
private:
DecoderBase* mDecoder;
};
int main()
{
Container container;
container.SetDecoder(new DecoderA());
((DecoderA*)container.GetDecoder())->GetDecodedFields();
return 0;
}
As you can see, before calling GetDecodedFields()
I have to cast it to one of the decoders, which is the exact reverse opposite of the purpose of polymorphism! How can I fix this code? I've also thought of using boost::dynamic_bitset
but I'd prefer not to use it for it's slower than normal bitset
.