c++ - 从语法和语义上下文来看,这个 C++ 模板语句实际上意味着什么
问题描述
请在下面找到 C++ 模板的一些用法。从句法和语义的角度来看,我无法完全理解这些,例如,首先声明这是我知道的:
template <class T>
class Queue {// some other statements};
然后声明,我部分理解,需要从句法和语义的角度知道它是什么意思:
template <class T>
class IntermittentQueue : Queue<T> {// some other statements};
最后是这些声明,我还是不完全理解
template <class T>
typename IntermittentQueue<T>::Node* IntermittentQueue<T>::getNode(const node_ptr nodePtr) {// some other statements };
解决方案
template <class T>
class IntermittentQueue : Queue<T> { /* some other statements */ };
这定义了一个新的模板类:
template <class T>
class IntermittentQueue { }
同时继承自另一个,例如:
class Base { };
class Derived : Base { };
只是,在这种情况下,基类是另一个模板类的实例:
template <typename T>
class Base { };
class Derived : Base<int> { };
使用派生类的模板参数作为模板参数(现在我们又回到了原始代码......)。
template <class T>
typename IntermittentQueue<T>::Node* IntermittentQueue<T>::getNode(const node_ptr nodePtr)
{ /* some other statements */ };
这是模板类的成员函数之一的实现。一步步:
template <class T> // the class we are speaking off is a template class
typename IntermittentQueue<T>::Node* // return value of the function
IntermittentQueue<T>::getNode // function name with (template) class scope specified
// (just as with SomeClass::someMemberFunction)
(const node_ptr nodePtr) // function parameter(list)
{ /* some other statements */ }; // function body
到目前为止很好,但返回类型可能需要进一步解释:
typename IntermittentQueue<T>::Node*
该函数返回一个指向Node
(模板)类的内部类类型对象的指针IntermittentQueue
:
IntermittentQueue<T>::Node*
由于内部类型是依赖类型,因此您需要明确告诉编译器这实际上是一个类型,这就是typename
关键字 then 的用途;有关详细信息:该主题已有另一个问题。
这里只是一个旁注:为指针 ( node_ptr
) 使用 typedef 是不好的做法,这只是信息隐藏,并没有提供任何有价值的东西(例外情况:指针用作某些内部资源的句柄,不打算在任何地方取消引用外部——然后显式隐藏指针性质是有效的)。
推荐阅读
- java - 为不同的布局更新 TextView
- laravel - 重复键值违反唯一约束 Laravel 和 Postgresql
- reactjs - 如果 setState() 不是 web api 而是 asynchroons,它是如何运行开始的场景
- sql - 表中缺少数据
- c# - C# 标志枚举按值或名称切换
- html - Bootstrap Nav Items 正确的下拉菜单问题
- flutter - 如何在颤动中重复更新倒数计时器
- php - mPDF div 结束行(可能)
- python - Pandas:ValueError:整数列在第 2 列中有 NA 值
- docker-compose - Gitlab-runner 未能删除权限被拒绝