简体   繁体   中英

How to shorten typename syntax for template class

I have a template class with an innter type defined like this:

template <class T>
class BinarySearchTree
{
private:
    struct Node
    {
        T m_value;
        Node* m_left;
        Node* m_right;

        Node(const T& value = T(), 
            Node* const left = nullptr,
            Node* const right = nullptr)
            : m_value(value)
            , m_left(left)
            , m_right(right)
        {

        }
    };

public:
    const Node* find(const T& value) const;
};


template <class T>
const typename BinarySearchTree<T>::Node* BinarySearchTree<T>::find(const T& value) const
{
 // some code here
}

So there are many functions that return Node* and every time it is very annoying to write typename BinarySearchTree<T>::Node* for function return type outside of the class. Is there a better way?

Use trailing return types:

template <class T>
auto BinarySearchTree<T>::find(const T& value) const -> Node* 
{
 // some code here
}

Everything after BinarySearchTree<T>::find is evaluated with the scope of the class.

This allows you to put the definitions outside of your class without using type-aliases to shorten the names.

You could introduce a template alias as:

template<typename T>
using Node = typename BinarySearchTree<T>::Node;


template <class T>
Node<T> const* BinarySearchTree<T>::find(const T& value) const
{
 // some code here
 return nullptr;
}

The "obvious" solution would be to put the function definitions inline inside the class, which is not always a good idea.

Another might be to use type-aliases with templates and the using keyword (supported from C++11 onward):

template<typename T>
using Node = typename BinarySearchTree<T>::Node;

Then you can use the ( global ) type-alias Node like

template <class T>
const Node<T>* BinarySearchTree<T>::find(const T& value) const
{
    // some code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM