c++ - 模板函数声明中函数名之后的第二个 <> 是什么?
问题描述
在 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;
}
typename C::iterator
里面有 什么template<typename C, typename V> vector<typename C::iterator> find_all
?我没有看到 <> 在函数名之前和之后。这个结构是什么以及它是如何表达的?他在书中写道
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;
,但它没有解释第二个 <> 用法。
解决方案
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<typename C::iterator>
,或“C 的迭代器向量”。
typename
这个问题解释了需要的原因:为什么在限定的依赖名称之前需要关键字“typename”,而不是在限定的独立名称之前?
一个更简单的例子,没有模板,它也用于<>
返回类型:
std::vector<int> generateNNumbers(std::size_t numberOfElements)
{
std::vector<int> res;
...
return res;
}
推荐阅读
- jquery - 如何将当前选定的下拉列表项分配给 jQuery 中的标签?
- php - WooCommerce NGINX 缓存和 wc-session cookie 添加到购物车问题
- java - 使用 getter 访问静态对象、“公共静态”或“私有静态”的最佳实践
- reactjs - 在使用功能时做出反应,它的属性未显示在屏幕上
- r - legend.box.background 多个 aes ggplot2
- javascript - 在 jQuery 中使用回调函数
- c# - 关注最后一行并在 Datagrid 中的 itemsource 加载后开始编辑
- java - java程序在比较2个文件时找出错误的列
- c++ - 带有 ostream_iterator 的 std::string
- javascript - 第一次成功迭代后函数崩溃(元素未附加到页面文档)