The reason this is NOT possible in C ++, but possible in Java / Python, is because: in the C ++ vector, the STL container store (returned by vector :: data ()) contains the entire instance of the object sequentially packed. Each item must be the same size. This allows quick and convenient handling. Therefore, suppose you define a template class A,
template <class T> class A{ int id; T obj; };
Its size will depend on the template variable "T obj". Pressing the same class A of another type of template T will make each element in the vector have different sizes, so this is not possible. The only way is to use the shared_ptr or unique_ptr vector of the base class. Both shared_ptr and unique_ptr are supported by C ++ 11 and Boost. Each element of a derived class can have different types of templates. Thus, when the base class pointer destructor is called, the derived class destructor is called. For example,
#include <memory> #include <vector> #include <iostream> #include <string> using namespace std; class A{}; template <class T> class AImpl : public A{ public: T obj; AImpl(T _obj):obj(_obj){} ~AImpl(){ cout << "Deleting " << obj << endl; } }; int main(int argc, char** argv) { AImpl <string>* a1 = new AImpl <string> ("string1234"); AImpl <int>* a2 = new AImpl <int> (1234); AImpl <double>* a3 = new AImpl <double> (1.234); vector <shared_ptr<A>> As; As.push_back(shared_ptr<A>(a1)); As.push_back(shared_ptr<A>(a2)); As.push_back(shared_ptr<A>(a3)); }
Remember to compile with -std = C ++ 11 to enable C ++ 11.
Output:
Deleting string1234 Deleting 1234 Deleting 1.234
And you get what you want! :)
In Java / Python, each object class variable is actually a pointer, so a Java A or Python array from A is equivalent to a C ++ array of pointers A. So you get essentially the same functionality without explicitly creating shared_ptrs.
xuancong84
source share