为什么Xcode让我编译这个自定义迭代器代码?

时间:2016-07-19 00:57:50

标签: c++ xcode c++11

我正在学习自定义迭代器,我写了这个玩具示例:

#include <iostream>
#include <iterator>
#include <algorithm>

bool IsOdd (int i) {
  return ((i%2)==1);
}

class MyIterator : std::iterator<std::forward_iterator_tag, int>
{
  int *p;
public:
  MyIterator(int* x) :p(x) {}
  MyIterator(const MyIterator& mit) : p(mit.p) {}
  MyIterator& operator++() {++p;return *this;}
  MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
  bool operator==(const MyIterator& rhs) {return p==rhs.p;}
  bool operator!=(const MyIterator& rhs) {return p!=rhs.p;}
  int& operator*() {return *p;}
};


int main () {
  int numbers[]={2,3,4,5,6};
  MyIterator from(numbers);
  MyIterator until(numbers+5);

  MyIterator ii = std::find_if(from, until, IsOdd);
  std::cout << "The first odd value is " << *ii << '\n';

  return 0;
}

在我的Apple计算机上,我可以使用clang ++编译此代码,其中包含版本“Apple LLVM版本7.3.0(clang-703.0.31)”。但是当我尝试在我的Ubuntu 14.04上编译代码时,我收到了这个错误:

In file included from iterators.cpp:5:
In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/5.3.0/../../../../include/c++/5.3.0/algorithm:62:
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.3.0/../../../../include/c++/5.3.0/bits/stl_algo.h:162:10: error: no matching function for call to '__iterator_category'
                       std::__iterator_category(__first));
                       ^~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.3.0/../../../../include/c++/5.3.0/bits/stl_algo.h:3790:19: note: in instantiation of function template specialization
      'std::__find_if<MyIterator, __gnu_cxx::__ops::_Iter_equals_val<const int> >' requested here
      return std::__find_if(__first, __last,
                  ^
iterators.cpp:37:24: note: in instantiation of function template specialization 'std::find<MyIterator, int>' requested here
  MyIterator ii = std::find(from, until, 31);
                       ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.3.0/../../../../include/c++/5.3.0/bits/stl_iterator_base_types.h:204:5: note: candidate template ignored: substitution failure
      [with _Iter = MyIterator]: no type named 'iterator_category' in 'std::iterator_traits<MyIterator>'
    __iterator_category(const _Iter&)
    ^
1 error generated.

我在Ubuntu上的clang ++版本是“Ubuntu clang版本3.4-1ubuntu3(标签/ RELEASE_34 / final)(基于LLVM 3.4)”“在这两种情况下我都用”-std = c ++ 11“标志进行编译。 / p>

我知道我可以通过公开继承std :: iterator来获取编译代码,但我的问题是:

  1. Ubuntu上的clang ++在发出错误时是正确的,还是Apple的clang ++没有报告错误?
  2. 编写自定义迭代器时,最好是一直公开继承std :: iterator吗?

0 个答案:

没有答案