friendoflore friendoflore - 2 months ago 10
C++ Question

C++ sibling template classes as template template parameters

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?

Answer

Following should be enough:

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