I haven’t used the advanced features of C++ for a while and am refreshing my C++ knowledge..
Having said that, the concept of traits and policy based programming was something that I never really managed to get my head around.
I want to change that. I am writing a generic container. I want to enforce a policy that the container will store only classes that derive from a particular base class. This is because the container returns an invalid object (instead of throwing) when an attempt is made to access an item outside the vector bounds.
template <class T>
class GenericContainer
{
private:
typedef std::vector<T> TypeVect;
void addElement(const T& elem);
TypeVect m_elems;
public:
unsigned int size() const;
T& elementAt(const unsigned int pos);
const T elementAt(const unsigned int pos) const;
};
How would I use traits to restrict this generic container to contain only subclasses of class ‘ContainerItem’ say?
You can use a little
IsDerivedFromtemplate which can only be instantiated in case a given type ‘D’ inherits another type ‘B’ (this implementation was taken from a nice Guru Of The Week article):You can now simply instantiate the
IsDerivedFromtemplate using inheritance:This code only compiles if
TinheritsContainerItem.