I have templated class vector<typename T,size S>
(I have to use this instead of std::vector
). I would like to specify an alias which is in type of vector<double,2>
, but I also need to count the amount of all created and all currently live objects of this. Here's fragment of my templated class:
template<typename T, size S>
class vector{
private:
T *_values;
public:
vector():
_values(new T[S]){
for(int i =0; i < S; i++)
_values[i] = T();
}
~vector(){
delete[] _values;
}
};
So I thought about creating class named vector2D
which inherits vector<double,2>
and with two additional static variables to count its amounts. But how to do that? How to invoke superclass constructor and destructor so that it only contains incrementation/decrementation of these two static variables? vector2D
is going to be used often in project I have to do. Maybe there is better solution?
PS How to pretty initialize *_values
? I tried *_values = { 0 }
but it didn't work (of course assuming this is going to be a table of primitive types).
I would like to specify an alias which is in type of
vector<double, 2>
Well that's simple:
typedef vector<double, 2> vector2D
but I also need to count the amount of all created and all currently live objects of this.
That's simple as well. Here's a small example:
#include <iostream>
template <typename T, int S>
class vec {
public:
vec() {
++obj_counter;
}
static int obj_counter;
};
template <typename T, int S>
int vec<T, S>::obj_counter = 0;
typedef vec<double, 2> vec2d;
int main() {
vec<int, 1> intvec1;
vec<int, 1> intvec12;
vec2d doublevec2;
std::cout << vec2d::obj_counter << std::endl;
return 0;
}
The advantage of this is the fact that obj_counter
works for every type. In the above example if you type:
std::cout << vec<int, 1>::obj_counter << std::endl;
It will print 2
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.