I would like to write some class which maps int to something using templates.
What I’m thinking of are generally two options:
1. unsigned int -> double (scalar)
2. unsigned int -> double[N] (vector of length N; N is the same for each int)
I write a class around
template <class T>
class int2type_storage {
public:
....
private:
typename std::map<unsigned int,T> map_;
}
With the first case, the usage is straightforward:
int2type_storage<double> map1;
The question is, what is the most efficient way/object for the second case?
I was thinking to do something like
int2type_storage< std::vector<double> >
but I have a feeling that this will be sub-optimal. Another option is to store pointers
int2type_storage< double* >
but then I have a problem that I should allocate memory for N elements outside of the map-class and take care to free it later.
EDIT1: Thank you guys for answering, I feel sorry that I can’t mark two answers as correct.
EDIT2:
I have implemented everything, but my linker could not find functions:
undefined reference to `int2type_storage<std::tr1::array<double, 4ul> >::init(int, int)'
.h:
template <class T>
class int2type_storage {
public:
int2type_storage() {};
~int2type_storage() {};
void init(const int number, const int index);
...
private:
int cur_index_;
typename std::map<unsigned int, T>::iterator iterator_;
typename std::vector<std::map<unsigned int,T> > map_vector_;
bool zero_initialized;
};
.cpp:
template<class T>
void int2type_storage< T >::init(const int length, const int max_index) {
map_vector_.resize(length);
}
usage:
int2type_storage< std::tr1::array<double, 4> > w_map_;
what’s wrong?
Assumming
Nis known at compile-time, you could use anstd::array<double,N>:I am not sure what the reasons for the
int2type_storagewrapper are, but you could also use a C++11 template typedef: