xiao su
xiao su

Reputation: 167

How to use a template class in another template class in c++

#include <stdio.h>

template <class T>
class BTreeNode {
public:
     BTreeNode(T d){data = d;};
private:
     T data;
};

template <class T, template<class> class Node>
class BTree {
private:
     Node<???> m_treeNodes; // I hope this type can be specified by the client, 
                            // but I don't know how to write here
     T m_data;
};


int main() {
     BTree<int, BTreeNode<int> > tree;// I don't know how to write here
     return 0;
}

so how can I do if I want one template class has a member variable of another template class. Or if my design has some problem? Thank you

Upvotes: 2

Views: 1404

Answers (2)

Galik
Galik

Reputation: 48615

Unless I have mistaken your intent I think you can just use the type T specified for the whole BTree something like this:

template<class T>
class BTreeNode
{
public:
    BTreeNode() {}
    BTreeNode(T d){data = d;};

private:
    T data;
};

template<class T>
class BTree
{
public:
    BTree() {}

private:
    BTreeNode<T> m_treeNodes; // just use T ?
};


int main()
{
    BTree<int> tree;
}

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172924

If you want the client specify the instantiation directly, you can just use a type template parameter instead of template template parameter, e.g.

template <class T, class Node>
class BTree {
private:
     Node m_treeNodes;  // use the type specified by client directly
     T m_data;
};

then

int main() {
     BTree<int, BTreeNode<int> > tree; // specify the instantiation at client
     return 0;
}

or you can add another type parameter, and determine the instantiation in the class template, which might be more flexible for some cases.

template <class T, template <typename> class Node, class X>
class BTree {
private:
     Node<X> m_treeNodes;  // determine the instantiation here
     T m_data;
};

then

int main() {
     BTree<int, BTreeNode, int> tree; // specify the types at client
     return 0;
}

Upvotes: 1

Related Questions