I have a template class something like :
template <class TYPE>
class Temp {
public:
Temp(TYPE _val) : var(_val){};
TYPE var;
};
I want to store the objects on this template class in a STL container say vector.
void print(vector<Temp<TYPE> *> & _vec) {
for(unsigned short i = 0; i < _vec.size() ; i++)
cout << " Value of stored variable is : " << (*_vec[i]).var << endl;
}
int main(int argc, char* argv[]) {
vector<Temp<TYPE> *> cont;
Temp<int> t1(20);
Temp<float> t2(1.4);
cont.push_back(&t1);
cont.push_back(&t2);
return 0;
}
I know that we cannot allocate a stl container without defining the type. Is there any way around to get this done ? and I cannot use boost.variant.
Your options include:
Giving the distinct instantiations of Temp
a common base class (with a virtual destructor), then storing pointers to the base type in the vector
. You can then use dynamic_cast<>
to check the run-time type of the stored objects, or you can add some type-indicating virtual function overridden in the derived instantiations.
Writing your own discriminated union class, where an enum or int keeps track of the current type stored (if there's a fixed set).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.