3

There are two classes A and B, where A is the base class and B is the derived class:

template <typename T>
class A {T a;};

template <typename T>
class B: public A <T> {T b;};

and the following class representing a modified container

template <typename Item>
struct TItems {typedef std::vector <Item> Type;};

template <typename Item>
class ModCont
{
    private:
            typename TItems <Item>::Type items;
};

A function test() has pointer to container of A objects as formal parameter:

template <typename T>
void test ( ModCont <A <T> > *it) {}

I would like to apply polymorphism and pass container of B to the method test:

int main(int argc, char* argv[])
{

  ModCont < A <double> > a_items;
  ModCont < B <double> > b_items;
  test (&a_items); //Works
  test (&b_items); //Does not work
  return 0;
}

The only way I found is to templatize a parameter of the test() method in this way:

template <typename Object>
void test ( ModCont <Object> *it) {}

Is there any way how to use the the "function" polymorphism instead of the compile polymorphism (templates?)

Thanks for your help...

justik
  • 4,145
  • 6
  • 32
  • 53
  • You are seriously confused: (1) Templates are a form of polymorphism (2) Templates are specialised at compile time, not runtime. – Marcin Jan 14 '12 at 10:08
  • 2
    Your function `test`, as given, is not a method but a free function. Please show minimal compilable code showing the problem, so we don't have to guess what you really did. – celtschk Jan 14 '12 at 10:13

3 Answers3

3

An apple is a fruit.

A bag of apples is not a bag of fruit. That's because you can put a pear in a bag of fruit.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
3

Uhm, first of all, templates are not runtime polymorphism -- they're compile-time polymorphism.

If you want to use runtime polymorphism with this, you have to make sure that ModCont<B<T> > derives from ModCont<A<T> > -- the way C++ handles polymorphism does not make this the default. Alternatively, you could have all ModCont<T> derive from some general ModContBase, although it's unclear how that would work.

Cactus Golov
  • 3,474
  • 1
  • 21
  • 41
  • Just for the note: you've not shown us `ModCont` being runtime-polymorphic in any other way, so I think templates are the way to go anyway (together with passing by reference). – Cactus Golov Jan 14 '12 at 10:16
0

You want to have your container be of A* rather than A. You also want a constructor which takes a container of U* and adds the contents of that container to itself. Use static_cast for this cast so that you have type-safety, i.e., U is a type derived from A.

Arnavion
  • 3,627
  • 1
  • 24
  • 31