【发布时间】:2021-01-08 22:43:02
【问题描述】:
看书A tour of c++ (second edition), 2018,没看懂模板的解释(下面我会解释)。
为find_all 函数提供了两个函数签名,该函数将iterators 中的vector 返回给给定container 中给定值的所有出现。
#1:
template<typename C, typename V>
vector<typename C::iterator> find_all(C& c, V v);
#2:
template<typename T>
using Iterator = typename T::iterator;
template<typename C, typename V>
vector<Iterator<C>> find_all(C& c, V v) ;
两者都可以这样使用:
string m {"Mary had a little lamb"};
for (auto p : find_all(m,'a')) // here p is a string::iterator
cout << *p << endl; // spoiler alert : this will print 'a's
#2 使用别名模板据说是
通过为 Iterator 引入类型别名来隐藏实现细节
作者。
虽然我认为我了解模板的两种用法,但我不明白为什么 #2 会“隐藏实现细节”以及为什么首选它......谁能解释一下?
谢谢!
postscriptum :我没有在帖子中提供函数的定义(两个签名相同),因为我认为它没有用,但如果有人需要,我会添加它.
【问题讨论】: