Re: r H2 deduce deduce template argument of a template class
inheriting from a non template base?
On 6 Mrz., 21:11, nguillot <nicolas.guil...@gmail.com> wrote:
Let's say I've got a template class inheriting from a non template
class:
struct SData
{
virtual ~SData() {}
};
Are you sure you don't need some more functions? Perhaps something
like this:
struct SData
{
virtual ~SData() {}
virtual void print_on(std::ostream&) const = 0;
};
That's what virtual functions are for. ;-)
template <class T>
struct SDataContainer : public SData
{
SDataContainer(const T& o) : m_data(o) {}
T m_data;
};
You could override "print_on" here.
void print(SData* pData)
{
SDataContainer<int>* pi = dynamic_cast<SDataContainer<int>*>
(pData);
if (pi != 0)
{
cout << "printing integer " << pi->m_data << endl;
return;
}
SDataContainer<bool>* pb = dynamic_cast<SDataContainer<bool>*>
(pData);
if (pb != 0)
{
cout << "printing bool " << (pb->m_data ? "true" :
"false") << endl;
return;
}
BTW: Is there a reason why you put this function inside a class or is
this only a habit you imported from Java / C# for no reason?
You're right. That looks ugly. You could avoid this with a virtual
function like SData::print_on :
void print(SData* pData)
{
pData->print_on(cout);
}
Now, the question: is there a way to avoid the dynamic_cast and deduce
the template argument thanks to template method specialization.
I would like to write something like that: [...]
template <class T>
void print(SDataContainer<T>* pData)
{
cout << "data type not handled" << endl;
}
template <>
void print(SDataContainer<int>* pData)
{
cout << "printing integer " << pData->m_data << endl;
}
(1) Specializing function templates is discouraged.
(2) Your syntax seems wrong: Shouldn't it be "print<int>" ?
(3) There's a big difference between the static type and the
runtime (most derived) type. The first one is known at
compile-time the 2nd one can only be determined at
run-time (in general). So, the compiler isn't able to select
the function with the right runtime type at compile-time.
That's what virtual functions are for.
Cheers!
SG