Vector and unspecialized class template

E

Ek.H

Hey,

I have a templated class (code follows) that I wish to put
into a vector, however I wish to put multiple of the class
into the vector and all might vary in what type they
represent.

Is there a way for me to to this without using multiple
vectors for each type of the class ?

(PS: I'm new to programming)


Code Snippet:

#include <iostream>
#include <vector>

template <typename T> class keeper {
private:
T& value;
public:
keeper(T& in_value) : value(in_value) {
}

~keeper () {
}
};

int main () {

float my_float_value = 0.1f;
int my_int_value = 129;

keeper<float> my_float(my_float_value);
keeper<int> my_int(my_int_value);

/* this one needs to be changed */
std::vector< keeper > my_keepers;

return(0);
}
 
V

Victor Bazarov

Ek.H said:

Hey yourself.
I have a templated class (code follows) that I wish to put
into a vector, however I wish to put multiple of the class
into the vector and all might vary in what type they
represent.

A standard vector is a template whose first argument is a class.
As soon as you try instantiating a vector, you need to provide
a *single* *complete* class. There can be no "multiple". Such
is the rule.
Is there a way for me to to this without using multiple
vectors for each type of the class ?

No.

However, if you want to keep different objects collected in
some kind of container, you should research "heterogeneous
container" on the web.
(PS: I'm new to programming)


Code Snippet:

#include <iostream>
#include <vector>

template <typename T> class keeper {
private:
T& value;
public:
keeper(T& in_value) : value(in_value) {
}

~keeper () {
}
};

int main () {

float my_float_value = 0.1f;
int my_int_value = 129;

keeper<float> my_float(my_float_value);
keeper<int> my_int(my_int_value);

/* this one needs to be changed */
std::vector< keeper > my_keepers;

return(0);
}

V
 
G

Gianni Mariani

Ek.H said:
Hey,

I have a templated class (code follows) that I wish to put
into a vector, however I wish to put multiple of the class
into the vector and all might vary in what type they
represent.

... What Victor said.

and

The way this is normally done is by storing pointers to a base class of
keeper<T> in the vector - or - by using an "any" class - like boost::any
or Austria C++ Any.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,635
Latest member
SkyePurves

Latest Threads

Top