I have something like this:
template <typename T, int N> class Data {
typedef Data<T, N> data;
public:
T y;
data *ptr[N];
};
And what I would like to able to add variables and functions to the class if N == 2
, for example:
template <typename T, int N> class Data {
typedef Data<T, N> data;
public:
T y;
data *ptr[N];
/* if N == 2, add the following members to the class */
int x;
data *left() { return ptr[0] };
data *right() { return ptr[1] };
};
I know one can use inheritance or specialization, but there is problems on both of them.
Inheritance doesn't make any sense in this specific case because the variable ptr
points to the same class, so if I use:
template <typename T> class Data2 : Data<T, 2> {
typedef Data2<T> data;
public:
int x;
data *left() { return ptr[0] }; // Error (ptr has type Data<T,N>)
data *right() { return ptr[1] }; // Error
};
the variable ptr
that Data2
inherits from Data
would point to the class Data
and not Data2
, rendering the base class useless.
The problem with specialization is that I would have to copy the entire base class to the specialization, and for smaller cases this might be okay, but if I have a really complex class or if I want custom variables and functions for several values of N
, that would be impractical.
I also know the existence of std::enable_if
which I think can solve the problem for functions, but it does not so for variables.
If anyone has a solution for it or a different approach that would bypass this, please let me know.