JayW JayW - 2 months ago 9
C++ Question

C++ How to have a vector of objects depending on template type

I have a template class C that which should contain a vector with E objects. The E objects in the vector will store the same type as the template is. So if the C object is of type

the vector should contain E objects that contain
, if C has
then E should store a
etc. The code looks like this:

template<class T> class C {
class E {
T value; //if C has type int then the events should store int
std::string description;
Event(std::string desc, T val) {
this->description = desc;
this->value = val;
virtual ~C();

bool add_e (std::string description);

T c_value;
std::vector<E> c_vector; //this should look somewhat like [E<int>, E<int>, E<int>]

And this compiles, but when I try to add elements to c_vector in the C.cpp file like this:

template<class T>
bool C<T>::add_e(std::string description) {
c_vector.add(E(description, c_value));

I get the error: 'class std::vector < C< int >::E, std::allocator< C< int >::E > >' has no member named 'add'. What is going on? How can I accomplish to store E objects which stores the same type as the enclosing template class type C?

When I try so search the web I only find information about storing different template types in a vector by for example making E a derived class of an abstract class and then store abstract class pointers in the vector, but I want all of the elements to contain the same type.


Use push_back() from std::vector