Home > Back-end >  error when declaring an inner class template field
error when declaring an inner class template field

Time:11-24

I have an error with the following code, using the inner template class Node. the error is when declaring the root private field:

"member root declared as a template".

template <typename KeyType, typename ValueType>
class TreapBST : public AbstractBST<KeyType, ValueType>
{
public:
    .....

private:
   template <typename K, typename V>
   struct Node
   {
       ....
   };

    template <typename K, typename V>
    typename TreapBST<K, V>::Node<K, V>* root = nullptr;

};

CodePudding user response:

I think you have the basic idea right but are getting the syntax confused.

When you write a class template you do not need to keep repeating template <typename K, typename V> for each member unless you want that K and V to be two types that are different from class parameters KeyType and ValueType. If you just need KeyType and ValueType you don't need to redeclare members as templates.

For example the following will compile:

template <typename KeyType, typename ValueType>
class AbstractBST
{
    //...
};

template <typename KeyType, typename ValueType>
class TreapBST : public AbstractBST<KeyType, ValueType>
{
public:
    //...

private:

    struct Node
    {
        KeyType key;
        ValueType val;
        //...
    };

    Node* root = nullptr;

};

int main()
{
    TreapBST<std::string, int> treap;
    return 0;
};
  • Related