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.
You can specialize your template declarations for particular values of N, and use another level of inheritance indirection for the common code in your base class, that doesn't depend on N:
template <typename T> class DataBase {
public:
T y;
};
template <typename T, int N> class Data : public DataBase {
typedef Data<T, N> data;
public:
data *ptr[N];
};
Also, without really knowing what you actually want there, I'd say something like
typedef T DataType;
typedef T* DataTypePtr;
in the base class makes more sense for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With