- I want a template class that defines the same algorithms, but can work on different type of data stored in a member variable.
- The exact type of data ideally depends only on a single template parameter.
- I don't want run time polymorphism (like have an argument of a pointer to base class that can accept all derive class).
Below is my current solution using variadic template. Is there a simpler/better way?
#include <vector>
class Data1 {
public:
Data1(int size, int stride)
: _v(size*stride), _size(size), _stride(stride) {}
int& operator[](int id) {return _v[id*_stride];}
const int _size;
private:
const int _stride;
std::vector<int> _v;
};
class Data2 {
public:
Data2(int size) : _v(size), _size(size) {}
int& operator[](int id) {return _v[id];}
const int _size;
private:
std::vector<int> _v;
};
template <typename Data, typename... Data_arg>
class Base_template {
public:
Base_template(Data_arg...data_arg): _data(data_arg...) {}
void set_all() {
for (int i = 0; i < _data._size; ++i) _data[i] = _val;
}
protected:
int _val;
Data _data;
};
class Thing1 : public Base_template<Data1, int, int> {
public:
Thing1(const int size)
: Base_template(size, 3) {
this->_val = 1;
}
};
class Thing2 : public Base_template<Data2, int> {
public:
Thing2(const int size)
: Base_template(size) {
this->_val = 10;
}
};
int main() {
Thing1 t1(100);
t1.set_all();
Thing2 t2(10);
t2.set_all();
}
Notes:
- I use variadic template because the data needs to be initialize.
- In the simple example above Data2 actually can be replaced by data1 with a stride of 1. But in the actually code, this is not the case.
Data2
as Dota2 \$\endgroup\$