【发布时间】:2021-01-14 12:58:32
【问题描述】:
在 Stroustrup “A Tour of C++”中,他写了 find_all 的示例
template<typename C, typename V>
vector<typename C::iterator> find_all(C& c, V v)
// find all occurrences of v in c
{
vector<typename C::iterator> res;
for (auto p = c.begin(); p!=c.end(); ++p)
if (∗p==v)
res.push_back(p);
return res;
}
template<typename C, typename V> vector<typename C::iterator> find_all 中的typename C::iterator 是什么?我没有看到 在函数名之前和之后。这个结构是什么以及它是如何表达的?
他在书中写道
The typename is needed to inform the compiler that C’s iterator is supposed to be a type and not a
value of some type, say, the integer 7. We can hide this implementation detail by introducing a type
alias (§6.4.2) for Iterator:
template<typename T>
using Iterator = typename T::iterator;
// T’s iterator
template<typename C, typename V>
vector<Iterator<C>> find_all(C& c, V v)
// find all occurrences of v in c
{
...
这并没有让事情变得更清楚。我了解using Iterator = typename T::iterator; 是什么,但它没有解释第二个 用法。
【问题讨论】:
-
这称为“模板”。在每本 C++ 教科书中,模板都是需要多章才能完全解释的东西。通过将这些章节复制/粘贴到 Stackoverflow 中为您提供答案不会很有成效。因此,您必须参考您的 C++ 教科书以获取更多详细信息和解释。
-
请注意,您选择的书不是初学者的介绍。它更像是“为有经验的 C++11 之前的程序员提供的新语言特性之旅”。如果您还不了解 C++,您将很难理解它。