如何缩短模板类的typename语法
How to shorten typename syntax for template class
我有一个内部类型定义的模板类:
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
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 为什么返回类型中需要typename?C++
- 单独定义模板化嵌套类方法的正确语法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 为什么我会收到错误 C2143 语法错误:缺少"*"之前的';'?
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 使用基类指针调用基类的值构造函数的语法是什么?
- 很好的语法来获取对向量/数组数据的大小引用?
- C++语法运算符功能?
- C++使用 rand 定义函数语法
- C 了解模板的语法,TypeName
- 'typename List::node_type& elem_node = elem->*list.node;'的语法含义是什么?
- 如何缩短模板类的typename语法