Вот определение шаблона класса < /p>
Код: Выделить всё
// GenericContainer.hpp
// --------------------------------------
class ContainerItem
{
protected:
virtual ContainerItem& getInvalid() = 0;
public:
virtual ~ContainerItem();
bool isValid() const;
};
template
class IsDerivedFrom
{
static void Constraints(D* p)
{
B* pb = p; // this line only works if 'D' inherits 'B'
pb = p; // suppress warnings about unused variables
}
protected:
void IsDerivedFrom2() { void(*p)(D*) = Constraints; }
};
// Force it to fail in the case where B is void
template
class IsDerivedFrom
{
void IsDerivedFrom2() { char* p = (int*)0; /* error */ }
};
template
class GenericContainer : public IsDerivedFrom
{
private:
typedef std::vector 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;
};
template
void GenericContainer::addElement(const T& elem)
{
m_elems.push_back(elem);
}
template
unsigned int GenericContainer::size() const
{
return m_elems.size();
}
template
T& GenericContainer::elementAt(const unsigned int pos)
{
unsigned int maxpos = m_elems.size();
if (pos < maxpos)
return m_elems[pos];
return T::getInvalid();
}
template
const T& GenericContainer::elementAt(const unsigned int pos) const
{
unsigned int maxpos = m_elems.size();
if (pos < maxpos)
return m_elems[pos];
return T::getInvalid();
}
// Class to be contained (PURPOSELY, does not derive from ContainerItem)
// Data.hpp
//----------------------------------------------------------------
class Data
{ /* implem details */};
// Container for Data items
// Dataset.h
// ----------------------------------------------------------------------------
#include "GenericContainer.hpp"
#include "Data.hpp"
class Dataset: public GenericContainer
{
public:
Data& getInvalid();
};
// C++ source
// -----------------------------------------------------------
#include "Dataset.hpp"
Dataset ds;
Данные класса не реализуют чистый виртуальный метод, объявленный в ABC ContainerItem. 4.4.3
Подробнее здесь: https://stackoverflow.com/questions/476 ... e-question
Мобильная версия