【问题标题】:What are second <> after function name in template funciton declaration?模板函数声明中函数名后的第二个 <> 是什么?
【发布时间】: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&lt;typename C, typename V&gt; vector&lt;typename C::iterator&gt; 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++,您将很难理解它。

标签: c++ c++11 templates


【解决方案1】:
template<typename C, typename V> //template declaration
vector<typename C::iterator> //return type (vector of iterators)
find_all //function name
(C& c, V v) //argument list

函数find_all 返回vector&lt;typename C::iterator&gt;,或“C 的迭代器向量”。

这个问题解释了为什么需要typenameWhy is the keyword “typename” needed before qualified dependent names, and not before qualified independent names?


一个更简单的例子,没有模板,它也在返回类型中使用&lt;&gt;

std::vector<int> generateNNumbers(std::size_t numberOfElements)
{
    std::vector<int> res;
    ...
    return res;
}

【讨论】:

  • 哦,构造类型名 C::iterator 混淆了,以至于我什至没有意识到它是返回值的一部分。非常感谢。
  • 有趣的是,我可以通过编写类似 C::iterator 的东西来为模板类型添加一些限制
  • @Johy 嗯,这是一些限制,但关键是find_all 期望类C 将有一个名为iterator 的内部类型或typedef(这是公开可见的)。然后它将该类型的向量返回给调用者。
  • 在您在示例中提供的链接中接受的答案中,有一行 T::template C z;你能告诉我什么是 T::template 吗?
  • @Johy 这是T::(template C)&lt;int&gt; z。这不是什么特殊的构造,它在名称C 之前添加了template 关键字。我相信解释也应该在那个答案中?旁注:在 C++ 方面有 3 年的专业经验,我从来没有发现它的用途。这是模板元编程的一个不起眼的部分。
猜你喜欢
  • 2020-08-10
  • 2019-10-17
  • 1970-01-01
  • 2011-08-27
  • 2015-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多