为什么Clang不喜欢boost :: transform_iterator?

Dan*_*iel 1 c++ boost clang c++11

使用Clang 8.0.1和Boost 1.70,以下程序

// transform.cpp
#include <vector>
#include <algorithm>
#include <iostream>

#include <boost/iterator/transform_iterator.hpp>

struct Foo
{
    int x;
};

struct XGetter
{
    auto operator()(const Foo& foo) const noexcept { return foo.x; }
};

int main()
{
    const std::vector<Foo> foos {{1}, {2}, {3}};
    using boost::make_transform_iterator;
    const auto first = make_transform_iterator(foos.cbegin(), XGetter {});
    const auto last = make_transform_iterator(foos.cend(), XGetter {});
    std::cout << *std::max_element(first, last) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

无法编译

$ clang++ -std=c++14 -o transform transform.cpp

/usr/local/Cellar/llvm/8.0.1/bin/../include/c++/v1/algorithm:2494:5: error: static_assert failed due to requirement
      '__is_forward_iterator<boost::iterators::transform_iterator<XGetter, std::__1::__wrap_iter<const Foo *>,
      boost::use_default, boost::use_default> >::value' "std::max_element requires a ForwardIterator"
    static_assert(__is_forward_iterator<_ForwardIterator>::value,
    ^             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/local/Cellar/llvm/8.0.1/bin/../include/c++/v1/algorithm:2512:19: note: in instantiation of function template
      specialization 'std::__1::max_element<boost::iterators::transform_iterator<XGetter, std::__1::__wrap_iter<const
      Foo *>, boost::use_default, boost::use_default>, std::__1::__less<int, int> >' requested here
    return _VSTD::max_element(__first, __last,
                  ^
transform.cpp:24:24: note: in instantiation of function template specialization
      'std::__1::max_element<boost::iterators::transform_iterator<XGetter, std::__1::__wrap_iter<const Foo *>,
      boost::use_default, boost::use_default> >' requested here
    std::cout << *std::max_element(first, last) << std::endl;
                       ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

我给人的印象是boost :: transform_iterator继承了它所建模的迭代器的迭代器类别。怎么了?

T.C*_*.C. 6

(C ++ 20之前的)标准需要前向或后向迭代器:

  • 取消引用时产生真实的引用;
  • 当两个相等的迭代器被取消引用时(即没有隐藏)产生对同一对象的引用

由于您的转型是按价值回报的,因此无法transform_iterator满足这两个要求。因此,它只能广告自己作为输入迭代器。

解决方法是更改XGetter为通过引用返回,或使用std::mem_fn(&Foo::x)为您执行的返回。

  • 有趣的!那么这是否意味着所有允许编译的编译器版本都不兼容? (2认同)
  • 不。该实现没有义务检查您是否确实将前向迭代器传递给了“max_element”。 (2认同)
  • 天哪,这很微妙。 (2认同)