【发布时间】:2016-12-17 22:15:04
【问题描述】:
我遇到了这个post,其中引入了可迭代队列。 OP 在实现中使用了来自std::queue 的名为c 的受保护变量。
这完全有效吗?这个变量在所有实现中都具有相同的名称吗?换句话说,标准是否明确规定这个变量必须命名为c?
【问题讨论】:
-
[queue.defn]中提到
我遇到了这个post,其中引入了可迭代队列。 OP 在实现中使用了来自std::queue 的名为c 的受保护变量。
这完全有效吗?这个变量在所有实现中都具有相同的名称吗?换句话说,标准是否明确规定这个变量必须命名为c?
【问题讨论】:
作为参考,std::queue 的确切定义列于here。所以回答
换句话说,标准是否明确规定该变量必须命名为
c?
是的,就是这种情况(其他容器适配器也类似);
template <class T, class Container = deque<T>>
class queue {
protected:
Container c;
// ...
};
但是,一般来说,受保护和私有名称和成员的名称不是标准化的,因为这些类型并非都是为了派生而构建的,并且实现是实现细节(并且不构成公共 API 的一部分);例如std::vector 没有列出任何受保护的名称。
一些std 容器和类确实定义了protected 成员的名称,特别是我想到的 iostreams 库 - 基本上是打算从中派生的类型。
作为跟进 - 所有编译器/库是否都使用 c?似乎至少主流的(libstdc++、libc++ 和 MSVC)是这样。 libstdc++ 的有趣之处在于它在变量上包含了follow comment;
/** * 'c' is the underlying container. Maintainers wondering why * this isn't uglified as per style guidelines should note that * this name is specified in the standard, [23.2.3.1]. (Why? * Presumably for the same reason that it's protected instead * of private: to allow derivation. But none of the other * containers allow for derivation. Odd.) */ _Sequence c;
【讨论】:
std::queue 的用法很奇怪且“不正常”。
std::array 有一个数据成员的名称,但有一个相关的评论,大意是 T elems[N]; // Exposition only。我不确定std::queue 中变量c 的动机是什么,它似乎早在C++98 就已经存在了。
length 这样的漂亮名称,那么应用程序可以通过执行#define length 0 来破坏实现。