Reputation: 151
is it possible to dynamically allocate a vector without specifying its Type ?
im creating a container class which should support all the numeric types it must creat a container vector which type will be specified later when the first number is pushed into it .
first of all is this code correct ?
private :
vector<int> stk ;
public :
template <typename Typ>
void push (Typ input)
{
vector<Typ> temp ;
stk = temp ;
}
second : i somehow need to dynamically allocate the "stk" vector without specifying the type .
Upvotes: 2
Views: 207
Reputation: 1404
If this is C++ code, then templates are specialized at compile time. You cannot delay the allocation of a vector -- or any other template class instance -- to runtime.
A workaround would be to customize your own numeric class hierarchy with base class, say CNumeric
, and allocate a vector of CNumeric*
. Then the vector can accommodate any numeric type in your own class hierarchy. But of course, this workaround can be very inefficient.
Upvotes: 2
Reputation: 2163
Usually you don't need to change the type of things at runtime (and you can't in C++). Typically you want to change the design of your program.
If you really want to do this, you could use a union type that can hold one of a different number of things like here:
union A {
int i;
float f;
double d;
};
and then store a vector of A.
Upvotes: 0
Reputation:
You haven't explained the problem correctly or you haven't understood what you really need.
If I understand correctly this is what you are looking for.
template<typename Typ>
class A {
private :
vector<Typ> stk ;
public :
void push (Typ input)
{
stk.push_back(input) ;
}
}
Upvotes: 1