声明一个接受泛型迭代器的函数

Sim*_* P. 21 c++ iterator

鉴于此代码,是否可以更改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)

该模板还将容器值类型的限制删除为字符串.请注意,您需要围绕它的括号++.

  • 虽然我认为这是最好的解决方案,但这不是他的问题的答案.(你至少应该用"为什么要限制字符串?"或者某些东西来证明你的回答是合格的,以明确你是在一条不太具体的路线上.) (5认同)

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/

http://www.boost.org/doc/libs/1_44_0/libs/type_traits/doc/html/boost_typetraits/reference/is_same.html

template<class I>
typename enable_if<
    is_same<typename iterator_traits<I>::value_type, string>
    >::type
function(...
Run Code Online (Sandbox Code Playgroud)

  • 仅供参考,现在可以在带有std :: is_same的C++ 11中使用它. (2认同)

Xav*_*olt 5

我认为没有你想要的那么简单。理想情况下,你可以做类似的事情

void dumpStrings(AbstractIterator<string> beg, AbstractIterator<string> end) { }
Run Code Online (Sandbox Code Playgroud)

但是 STL 迭代器似乎没有任何继承层次结构,这很令人恼火。所以看起来你被困在使用函数模板- 这就是它在STL Algorithms Library 中的完成方式。

抱歉 - 我也希望有更好的方法,但这是必须的。只记得在头文件中声明完整的函数模板!