首页 > 解决方案 > 模板函数声明中函数名之后的第二个 <> 是什么?

问题描述

在 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;,但它没有解释第二个 <> 用法。

标签: c++c++11templates

解决方案


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;
}

推荐阅读