10

I have a class named ABC which has a class template:

template <class T> class ABC{}

In another class I am trying to store of objects ABC in a list:

class CDE{
private:
  list<ABC *> some_list; 
}

I intend to store objects of ABC which might have different class template parameters. Is it necessary to specify template even for a pointer at compile time? What if the container is supposed to store objects of different type? Is that not possible?

Julio Gorgé
  • 10,056
  • 2
  • 45
  • 60
cyrux
  • 233
  • 5
  • 15

3 Answers3

10

Is it necessary to specify template even for a pointer at compile time ?

Yes.

What if the container is supposed to store objects of different type ? Is that not possible ?

It is not (directly) possible.

There is no such thing as the class ABC. There are only instantiations of ABC, such as ABC<Foo> and ABC<Bar>. These are completely different classes.

You can do something like:

template<typename T>
class ABC : public ABC_Base
{
  ...
}

list<ABC_Base*> some_list;

By doing this, all of your ABC instantiations have a common base type, and you can use a base pointer arbitrarily.

Tim
  • 8,912
  • 3
  • 39
  • 57
  • 1
    This sounds reasonable enough, with a little downside. The whole reason for using templates was the make sure that objects were tightly coupled. This way there is still a chance of creating objects of ABC_Base (or its derived classes) without template type and use them in the list. – cyrux Feb 24 '11 at 00:02
  • 4
    @cyrux If you make `ABC_Base` abstract, then nobody can create objects of `ABC_Base`. – user470379 Feb 24 '11 at 00:09
1

You need to either specify the template parameters in your CDE class, or make CDE a template as well.

First option:

class CDE {
private:
    list< ABC<int>* > some_list;
};

Second option:

template <class T>
class CDE {
private:
    list< ABC<T>* > some_list;
};
user470379
  • 4,879
  • 16
  • 21
1

The list can only store a single type. Different instantiations of a template are different types. If this is satisfactory, you can do it like this:

template <class T> class CDE{ private: list<ABC<T> *> some_list; }

If you need to use different types, perhaps you could create a non-template base class for ABC and store pointers to that. (ie. use an interface)

Alex Deem
  • 4,717
  • 1
  • 21
  • 24