friendoflore - 11 months ago 53

C++ Question

I have a binary tree and I am trying to put each depth of nodes in its own linked list.

I have the class templates:

`template <typename T>`

class Node

{

public:

T data;

};

template <typename T>

class ListNode : public Node<T>

{

public:

ListNode * next;

};

template <typename T>

class TreeNode : public Node<T>

{

public:

TreeNode * left;

TreeNode * right;

};

To accomplish the task, I planned on using a function template that has

`TreeNode<T> * root`

`vector<ListNode<T> *>`

What is the correct way to define the function template?

Not knowing how to approach it, I initially expected something like this to be a way to accomplish this:

`template <template <typename> class Node, typename T>`

std::vector<ListNode<T> *> listify(TreeNode<T> * root)

{

// Do stuff...

}

But this does not work.

It seems like the compiler is okay with:

`template <template <typename> class TreeNode, typename T>`

std::vector<ListNode<T> *> listify(TreeNode<T> * root)

{

// Do stuff...

}

Why does this work/what exactly is happening here? Is this the correct way to do this with sibling class templates?

Answer Source

Following should be enough:

```
template <typename T>
std::vector<ListNode<T>*> listify(TreeNode<T>* root)
```