繁体   English   中英

在模板向量上返回迭代器

[英]Returning an iterator over a template vector

我一直在寻找类似但却找不到的东西(或者我找到的东西没有帮助)。 我试图在模板类的向量上有一个迭代器,返回它并在类之外使用它,如下面的代码所示。

#include <iostream>
#include <vector>

using namespace std;

namespace ns {

 template <class T>
 class test {

  private:
   vector<T> container;

  public:
   typedef vector<T>::iterator iterator;

   vector<T>::iterator begin() {
    return container.begin();
   }

   vector<T>::iterator end() {
    return container.end();
   }

 }

};

int main(void) {
 test<int> inters;

 for (ns::test<int>::iterator i = inters.begin(); i != inters.end(); i++) {
  // bla bla bla
 }

 cout << "end" << endl;
 return 0;
}

(你也可以在这里查看代码: http//codepad.org/RuXCYF6T

我在第15行得到以下错误:

error: type '__gnu_debug_def::vector<_Tp, std::allocator<_CharT> >' is not derived from type 'ns::test<T>'
compilation terminated due to -Wfatal-errors.

提前致谢。

我得到的错误与你不一样(缺少typename ,缺少;缺少ns:: typename 显然,不同的错误消息来自不同版本的GCC。 你在g ++ 4.1.2下运行了这个。 我用的是g ++ 4.6.1。

修复所有错误后,这对我有用:

#include <iostream>
#include <vector>

using namespace std;

namespace ns {

 template <class T>
 class test {

  private:
   vector<T> container;

  public:
   typedef typename vector<T>::iterator iterator; // first change: add typename

   typename vector<T>::iterator begin() { // 2nd: add typename
    return container.begin();
   }

   typename vector<T>::iterator end() { // 3rd: add typename
    return container.end();
   }

 }; // 4th: add semi

} // 5th: delete semi

int main(void) {
 ns::test<int> inters; // 6th: add ns::

 for (ns::test<int>::iterator i = inters.begin(); i != inters.end(); i++) {
  // bla bla bla
 }

 cout << "end\n"; // 7th: avoid endl
 return 0;
}

另见: http//codepad.org/gcJBCFOD

您需要使用typename

typedef typename vector<T>::iterator iterator;

typename vector<T>::iterator begin()
typename vector<T>::iterator end()

编辑:
或者只使用你的typedef:

iterator begin()
iterator end()

有许多关于模板和类型名称和相关名称的讨论在这里 我很难找到那个页面。 这是我在那里发布的答案:

显然,当函数不是类成员时,所需的语法略有不同。 请注意返回类型周围的括号 - 编译器在没有它们的情况下抱怨。

template<typename T> (typename std::vector<T>::iterator)
              someNonMemberFunction(std::vector<T>& vec, const T& val)
{  return [some std::vector<T>::iterator to an element in vec];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM