0

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 as a parameter and returns a 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?

moth
  • 226
  • 2
  • 9
  • `TreeNode` does not need to be a template parameter there. As @jarod42 implies, you can just refer to the `TreeNode` class. The only template parameter you need is for the `T` of TreeNode. – caps Sep 14 '16 at 23:01

1 Answers1

3

Following should be enough:

template <typename T>
std::vector<ListNode<T>*> listify(TreeNode<T>* root)
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Thanks! The question I (wrongly) thought I was asking was using templates for the class templates as well. Something like `std::vector *> listify (N * root)`. I was confused. Thanks again! – moth Sep 15 '16 at 07:04