JayW JayW - 3 months ago 11
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

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

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

bool add_e (std::string description);

private:
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.

Answer

Use push_back() from std::vector

Comments