Newbie: Templates complication

R

Rach

Hi,

Is it possible for me to create a class Node that has a pointer to a class
Node. i.e.:

template <class T> class Node {
public:
Node (T t, int n) { ptrChild = t; nValue = n; };
private:
T* ptrChild;
int nValue;
};

How do I instantiate such class?

thanks much,
Rach
 
K

Karl Heinz Buchegger

Rach said:
Hi,

Is it possible for me to create a class Node that has a pointer to a class
Node. i.e.:
Sure


template <class T> class Node {
public:
Node (T t, int n) { ptrChild = t; nValue = n; };

From the way you use 't', I think it must be
Node (T* t, int n) { ptrChild = t; nValue = n; };
private:
T* ptrChild;
int nValue;
};

How do I instantiate such class?

eg.
struct Test
{
int a, b;
};

Test StructA;
Node<Test> NodeA( &StructA, 3 );
 
J

John Harrison

Rach said:
Hi,

Is it possible for me to create a class Node that has a pointer to a class
Node. i.e.:

template <class T> class Node {
public:
Node (T t, int n) { ptrChild = t; nValue = n; };
private:
T* ptrChild;
int nValue;
};

I think perhaps you mean this

template <class T> class Node {
public:
Node (Node<T>* t, T n) { ptrChild = t; nValue = n; };
private:
Node<T>* ptrChild;
T nValue;
};
How do I instantiate such class?

Same as any other class. Classes containing pointers to their own type
aren't a problem in C++, even when they are templates.
thanks much,
Rach

john
 
R

Rach

template <class T> class Node {
public:
Node (Node<T>* t, T n) { ptrChild = t; nValue = n; };
private:
Node<T>* ptrChild;
T nValue;
};

How do I instantiate this class? Node trial = Node<Node<Node>>; doesn't
work.

Thanks much,
Rach
 
K

Karl Heinz Buchegger

Rach said:
template <class T> class Node {
public:
Node (Node<T>* t, T n) { ptrChild = t; nValue = n; };
private:
Node<T>* ptrChild;
T nValue;
};

How do I instantiate this class? Node trial = Node<Node<Node>>; doesn't
work.

Node<int> trialA( NULL, 2 );
Node<int> trialB( trialA, 3 );
 
J

John Harrison

Rach said:
template <class T> class Node {
public:
Node (Node<T>* t, T n) { ptrChild = t; nValue = n; };
private:
Node<T>* ptrChild;
T nValue;
};

How do I instantiate this class? Node trial = Node<Node<Node>>; doesn't
work.

Thanks much,
Rach

I think you are confused, T is the type of data that each node holds, it has
nothing to do with the fact that each node points to another node.

Node<int> trial(NULL, 123);

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

templates?? 2
Chatbot 0
Implementing Many Stacks in the Same Program 1
Templates and g++ 4
Variadic templates std::tuple 2
Templates with two params 4
variadic templates - compile error 4
templates 10

Members online

Forum statistics

Threads
474,170
Messages
2,570,925
Members
47,468
Latest member
Fannie44U3

Latest Threads

Top