Narek Narek - 3 months ago 12
C++ Question

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?

Answer

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.