I have a template class named Cell as follows:-
templateclass Cell
{
string header, T data;
}
Now I want another class N
The reason why this is NOT possible in C++, but possible in Java/Python is because: in a C++ vector, the STL container's storage (returned by vector::data()) contains all the object instantiations sequencially packed. In which each element must have the same size. This makes addressing fast and convenient. Therefore, suppose you define a template class A,
template
class A{
int id;
T obj;
};
Its size will depend on the template variable "T obj". Pushing the same class A of different template type T will make each element in the vector having different sizes, thus, this is impossible. The only way is to use vector of shared_ptr or unique_ptr of a base class. Both shared_ptr and unique_ptr are supported by C++11 and Boost. Each derived-class element can have different template types. In this way, when the base class pointer's destructor is called, the derived class's destructor will be invoked. For example,
#include
#include
#include
#include
using namespace std;
class A{};
template
class AImpl : public A{
public:
T obj;
AImpl(T _obj):obj(_obj){}
~AImpl(){
cout << "Deleting " << obj << endl;
}
};
int main(int argc, char** argv)
{
AImpl * a1 = new AImpl ("string1234");
AImpl * a2 = new AImpl (1234);
AImpl * a3 = new AImpl (1.234);
vector > As;
As.push_back(shared_ptr(a1));
As.push_back(shared_ptr(a2));
As.push_back(shared_ptr(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, every class-object variable is actually a pointer, thus, a Java Array of A or a Python list of A is equivalent to a C++ array of pointers of A. Thus, you get essentially the same functionality without explicit creating shared_ptrs.