Sam
10/10/2008 10:16:00 PM
lhommedumatch writes:
> Hi,
> I have a derived template class and I want to call a method of the
> derived class from the base class.
> But the method need a template parameter.
> How can I do?
>
> Here is the code that doesn't work.
>
> #include <iostream>
> #include <string>
>
> using namespace std;
>
> //==============================================================
> class A
> {
> public:
> A()
> {
> std::cout << "constructeur de A" << std::endl;
> }
> ~A()
> {
> std::cout << "destructeur de A" << std::endl;
> }
> };
>
> //==============================================================
> template <class T> class B: public A
> {
> public:
> B():A()
> {
> std::cout << "constructeur de B" << std::endl;
> }
> ~B()
> {
> std::cout << "destructeur de B" << std::endl;
> }
> T _value;
> void setValue(T p_value)
> {
> _value = p_value;
> }
> };
>
>
> //==============================================================
> int main()
> {
> A *a = new B<int>;
> a->setValue(23131);
> delete a;
> }
> //==============================================================
>
> Thanks
There are several ways to do this.
The easiest way, and is probably what your real intention is, is to declare
setValue() as a pure virtual function in class A:
virtual void setValue(int)=0;
You can also declare ~A() as a virtual destructor. This will enable you to
use dynamic_cast<> to obtain the pointer to your subclass, and invoke it's
setValue() method.