Template classes and containers

P

Prakash Bande

Hi,

I have a template class as below:
template <class _T> class myclass{
public:
myclass(){ obj = new _T();}
_T* obj;
_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

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>*
}

Any suggestions?

Thanks,
Prakash
 
A

Alf P. Steinbach

* 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,175
Messages
2,570,946
Members
47,496
Latest member
Julieta51R

Latest Threads

Top