鉴于此代码,是否可以更改dumpStrings()为能够迭代任何容器string,比如说list<string>?
#include <vector>
#include <string>
#include <ostream>
#include <iostream>
using namespace std;
void dumpStrings(vector<string>::iterator it, vector<string>::iterator end)
{
while (it != end) {
cout << *it++ << endl;
}
}
int main()
{
vector<string> strVector;
strVector.push_back("Hello");
strVector.push_back("World");
dumpStrings(strVector.begin(), strVector.end());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Fox*_*x32 26
创建一个模板
template<class iterator_type>
void dumpStrings(iterator_type it, iterator_type end)
{
while (it != end) {
cout << *(it++) << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
该模板还将容器值类型的限制删除为字符串.请注意,您需要围绕它的括号++.
Any*_*orn 13
是
http://www.boost.org/doc/libs/1_45_0/libs/utility/enable_if.html
http://www.cplusplus.com/reference/std/iterator/iterator_traits/
template<class I>
typename enable_if<
is_same<typename iterator_traits<I>::value_type, string>
>::type
function(...
Run Code Online (Sandbox Code Playgroud)
我认为没有你想要的那么简单。理想情况下,你可以做类似的事情
void dumpStrings(AbstractIterator<string> beg, AbstractIterator<string> end) { }
Run Code Online (Sandbox Code Playgroud)
但是 STL 迭代器似乎没有任何继承层次结构,这很令人恼火。所以看起来你被困在使用函数模板- 这就是它在STL Algorithms Library 中的完成方式。
抱歉 - 我也希望有更好的方法,但这是必须的。只记得在头文件中声明完整的函数模板!