I define a Node class with template for its value type
template<class T>
class Node {
T val;
public:
Node (T & v) : val (v) {}
...
void print() { cout << v << endl; }
}
Most times, the node value of interest will be an object class, say class Foo
. In that case, use Node<Foo *>
will be more convenient. But it could also be that the node will hold primitive time, say int
. Then use Node<int>
will suffice.
The problem is, some of the function may need to behave differently based on whether T
is a pointer type or not. For example, print
should cout << *v
when it is and cout << v
otherwise.
What I've tried is to define both:
template<class T>
class Node {
T val;
public:
Node (T & v) : val (v) {}
...
void print() { cout << v << endl; }
}
template<class T>
class Node<T*> {
T* val;
public:
Node (T* v) : val (v) {}
...
void print() { cout << *v << endl; }
}
It now can choose the appropriate definition based on whether it's Node<int> or Node<int *>
But the problem become, the two definitions will share many code. I'm wondering whether there's better way to achieve this.