如何缩短模板类的typename语法

How to shorten typename syntax for template class

本文关键字:typename 语法 何缩短      更新时间:2023-10-16

我有一个内部类型定义的模板类:

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
}

所以有很多函数返回Node*,每次在类之外为函数返回类型编写typename BinarySearchTree<T>::Node*是非常烦人的。有没有更好的办法?

使用尾随返回类型:

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

BinarySearchTree<T>::find之后的所有内容都用类的作用域求值。

这允许您将定义放在类的外部,而无需使用类型别名来缩短名称。

您可以引入一个模板别名:

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;
}

"显而易见"的解决方案是将函数定义内联放在类中,这并不总是一个好主意。

另一种可能是对模板和using关键字使用类型别名(从c++ 11开始支持):
template<typename T>
using Node = typename BinarySearchTree<T>::Node;
然后你可以使用(全局)类型别名Node,如
template <class T>
const Node<T>* BinarySearchTree<T>::find(const T& value) const
{
    // some code here
}