Re: Template classes and containers

From: Alf P. Steinbach (alfps_at_start.no)
Date: 09/02/04


Date: Thu, 02 Sep 2004 05:15:48 GMT


* Prakash Bande:
>
> I have a template class as below:
> template <class _T> class myclass{

Underscore followed by uppercase letter is reserved for the
implementation.

> public:
> myclass(){ obj = new _T();}
> _T* obj;

This data member should not be public.

> _T* operator->() (return obj;}
> };

>
> I need to keep all the myclass objects in a STL container such as
> vector. But since every instantiation is a different type I cannot
> have a vector or myclass.
> So I derived myclass from a base class as below:
> class base{
> public:
> base(){}
> ~base(){}
> };
> template class<_T> myclass : public base

STL or standard library container requires among other things that your
objects can be safely copied -- can they?

 
> Now I have a vector of base objects.
> The problem is that I want to call -> operator. I cannot make it pure
> virtual in base since the return type depends on template resolution.
> I cannot typecast base pointer since I do not know type because of
> template. For example:
> f()
> {
> base *a = new myclass<someclass>
> f1(a);
> }
> void f1(base *a)
> {
> // I want to do this here.
> a->callmethod(); // Would have worked if -> could return
> myclass<someclass>*
> }

Try to explain why you "need" to have these objects in a single container,
or why you "need" to have them of different types.

-- 
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?


Relevant Pages

  • Re: Statically AND Dynamically Typed Language ??
    ... (say easier to implement the language) ... typing instead of with the template mechanisms? ... element type you have an independent instance of the container type. ... You mean for generics, right? ...
    (comp.lang.misc)
  • Re: Maintance of c++ code
    ... iterator constant in the standard, ... template ... template <class Iter_> ... container, some only work with particular containers. ...
    (comp.object)
  • Re: Teaching 5th graders
    ... used a heavy tissue paper over the cups and I had pre-cut 'windsheilds' of clay. ... I like the idea of the toothbrush and tarpaper - may use it ... Wrap the paper on the container ... Your template will ...
    (rec.crafts.pottery)
  • Re: C++ template tutorial/review : comments welcomed
    ... I agree that the statement about 'unified object model' and 'template ... that of C++ template class, but I have not come seen any papers about it. ... > multiple types into a container, you need to keep track of what type they ... Introducing generics in the CLR ...
    (comp.lang.cpp)
  • Re: trait technique?
    ... > polymorphic pointer for template class)? ... A container cannot contain different types. ... A vector of int will always ... class BoolConverter: public Converter ...
    (comp.lang.cpp)