Re: templated class : constructor specialization
Okay: here's what I came up with, after your much appreciated
comments. Instead of a helper class, I'm trying to use a common base
class for the main template, and its specialization.
Any comment will be much appreciated!
Thanks again.
==========================
// *** COMMON BASE CLASS ***
template <typename T>
class ATemplateClassCommonInterface
{
protected:
const T* const mpData;
int mCounter;
protected:
ATemplateClassCommonInterface(const T* apData, int aCounter = 0) :
mpData(apData), mCounter(aCounter) { }
public:
virtual ~ATemplateClassCommonInterface() { }
// COMMON INTERFACE --- TO BE IMPLEMENTED IN DERIVED TEMPLATES
virtual void specializedMethod() = 0;
// COMMON INTERFACE --- IMPLEMENTED HERE
void commonMethod()
{
std::cout << "commonMethod : mCounter = " << this->mCounter <<
std::endl;
this->mCounter++;
}
};
// *** MAIN CLASS TEMPLATE ***
template <typename T>
class CTemplateClass : public ATemplateClassCommonInterface<T>
{
public:
CTemplateClass(const T& aData) :
ATemplateClassCommonInterface<T>(new T(aData), 0)
{
std::cout << "CTemplateClass<T>::CTemplateClass : *mpData = "
<<
*(this->mpData) << std::endl;
}
virtual ~CTemplateClass()
{
delete this->mpData;
}
void specializedMethod()
{
std::cout << "CTemplateClass<T>::specializedMethod" <<
std::endl;
}
};
// *** SPECIALIZED CLASS TEMPLATE ***
template <typename T>
class CTemplateClass<T*> : public ATemplateClassCommonInterface<T>
{
public:
CTemplateClass(const T* apData) :
ATemplateClassCommonInterface<T>(apData, 10)
{
std::cout << "CTemplateClass<T*>::CTemplateClass : *mpData = "
<<
*(this->mpData) << std::endl;
}
virtual ~CTemplateClass()
{
// Show some manners.
//delete this->mpData;
}
void specializedMethod()
{
//AHelper_TemplateClass<T>::specializedMethod(this);
std::cout << "CTemplateClass<T*>::specializedMethod" <<
std::endl;
}
};
==========================
In the Main function,
CTemplateClass<int>* pTC1 = new CTemplateClass<int>(10);
CTemplateClass<int*>* pTC2 = new CTemplateClass<int*>(new int(15));
pTC1->commonMethod();
pTC2->commonMethod();
pTC1->specializedMethod();
pTC2->specializedMethod();
delete pTC1;
delete pTC2;
Output:
CTemplateClass<T>::CTemplateClass : *mpData = 10
CTemplateClass<T*>::CTemplateClass : *mpData = 15
commonMethod : mCounter = 0
commonMethod : mCounter = 10
CTemplateClass<T>::specializedMethod
CTemplateClass<T*>::specializedMethod
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]