Re: virtual functions and templates

From: tom_usenet (tom_usenet_at_hotmail.com)
Date: 11/06/03


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



Relevant Pages

  • Simple script annimation problem usig swing
    ... To change this template, ... public void destroy{ ... public state cstate; ... public static int respawn = 20; ...
    (comp.lang.java.programmer)
  • Re: Simple script annimation problem usig swing
    ... To change this template, ... public void destroy{ ... public state cstate; ... public static int respawn = 20; ...
    (comp.lang.java.programmer)
  • implementation details
    ... template class ) ... Retrieve then I'd like to implement some sort of overrun check. ... BUFFER(); ... unsigned int retrieve_count; ...
    (comp.lang.cpp)
  • Re: Replacing merge fields in headers/footers
    ... database, and a newly populated document can be requested at any time. ... to my way of thinking is to have a merge template ... I'm using exactly the same code to populate the fields in the ... >> private FileStream PopulateTemplateDocument(int theFileID, ...
    (microsoft.public.word.vba.general)
  • friend ostream& operator<< (ostream&, Array<T>&);
    ... Array(int itsSize = DefaultSize); ... int GetSize() const ... make sure the function template has already been declared and add after ... // implement the Constructor ...
    (alt.comp.lang.learn.c-cpp)