Re: virtual functions and templates
From: tom_usenet (tom_usenet_at_hotmail.com)
Date: 11/06/03
- Next message: tom_usenet: "Re: istrstream class to be replaced"
- Previous message: Ivan Vecerina: "Re: Deleting items from std::map in a loop"
- In reply to: SainTiss: "Re: virtual functions and templates"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 06 Nov 2003 17:33:53 +0000
On Thu, 06 Nov 2003 16:47:16 GMT, SainTiss <stiss@gmx.net> wrote:
>tom_usenet wrote:
>
>> On Wed, 05 Nov 2003 22:41:03 GMT, SainTiss <stiss@gmx.net> wrote:
>>
>>>tom_usenet wrote:
>>>> template <class T>
>>>> class CommonStuff
>>>> {
>>>> // non-virtual functions, casting this
>>>> // to a Derived* if necessary
>>>> };
>>
>>>I think I get the first alternative, but this one puzzles me a bit... How
>>>can the CommonStuff class cast to a Derived* if it doesn't know Derived?
>>>It only knows T from what I can see...
>>>
>>>So how exactly is this supposed to work then?
>>
>> Copy and paste error - ignore that comment!
>>
>> Tom
>
>Ok, but ignoring that comment, I don't really see how this is alternative is
>going to avoid polymorphism? How can the CommonStuff class call a
>specialized method if it doesn't know about the Derived class and can't use
>polymorphism?
It does know about the derived class if there is only one derived
class:
template <class T>
struct Derived;
template <class T>
struct Base
{
int f()
{
return static_cast<Derived<T>*>(this)->g() + 1;
}
};
template <class T>
struct Derived: public Base<T>
{
int g()
{
return 10;
}
};
template <>
struct Derived<int> : public Base<int>
{
int g()
{
return 3000;
}
};
#include <iostream>
int main()
{
Derived<double> d;
std::cout << d.f() << '\n';
Derived<int> i;
std::cout << i.f() << '\n';
}
The more general solution (for multiple derived classes) is the other
one I presented.
Tom
- Next message: tom_usenet: "Re: istrstream class to be replaced"
- Previous message: Ivan Vecerina: "Re: Deleting items from std::map in a loop"
- In reply to: SainTiss: "Re: virtual functions and templates"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|