在模板上使用模板别名

看书A tour of c++ (second edition), 2018,没看懂模板的解释(后面会解释)。

为一个find_all函数给出了两个函数签名,该函数将 avectoriterators返回到给定 中给定值的所有出现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:我没有提供带有函数定义的帖子(两个签名相同),因为我认为它没有用,但如果有人需要,我会添加它。

回答

假设您有一个代码库,例如

template<typename C, typename V>
vector<typename C::iterator> first(C& c, V v);
template<typename C, typename V>
vector<typename C::iterator> second(C& c, V v);
template<typename C, typename V>
vector<typename C::iterator> third(C& c, V v);
template<typename C, typename V>
vector<typename C::iterator> fourth(C& c, V v);
...

如果您决定要更改为返回向量const_iterator而不是iterator,则需要更改所有这些函数。使用时

template<typename T>
using Iterator = typename T::iterator;
template<typename C, typename V>
vector<Iterator<C>>  first(C& c, V v);
template<typename C, typename V>
vector<Iterator<C>>  second(C& c, V v);
template<typename C, typename V>
vector<Iterator<C>>  third(C& c, V v);
template<typename C, typename V>
vector<Iterator<C>>  fourth(C& c, V v);

你所要做的就是改变

template<typename T>
using Iterator = typename T::iterator;

template<typename T>
using Iterator = typename T::const_iterator;

你就完成了。这就是它“隐藏实现细节”的方式。


以上是在模板上使用模板别名的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>