为什么有变异Boost.Range算法的const重载?

aki*_*kim 6 c++ boost c++11 c++14 range-v3

Boost.Range的文档(和实现)显示了将const ref作为参数的变异算法的重载.例如Boost.Range的Sort文档显示:

template<class RandomAccessRange>
RandomAccessRange& sort(RandomAccessRange& rng);

template<class RandomAccessRange>
const RandomAccessRange& sort(const RandomAccessRange& rng);

template<class RandomAccessRange, class BinaryPredicate>
RandomAccessRange& sort(RandomAccessRange& rng, BinaryPredicate pred);

template<class RandomAccessRange, class BinaryPredicate>
const RandomAccessRange& sort(const RandomAccessRange& rng, BinaryPredicate pred);
Run Code Online (Sandbox Code Playgroud)

重载2和4有什么意义?当然能够通过临时工很好,但是const&这一点有点没有实际意义.Rvalue-references是最受欢迎的,但我的理解是他们对Boost.Range的支持太具侵略性,并且"延迟"采用Range.V3(如果同时它是Boost的一部分会很好).

Yak*_*ont 6

template<class T>
struct span_t {
  T* b =0;
  T* e =0;
  T* begin() const { return b; }
  T* end() const { return e; }
  std::size_t size() const { return end()-begin(); }
  bool empty() const { return size()==0; }
  T& operator[](std::size_t i) const { return b[i]; }
  span_t()=default;
  span_t(span_t const&)=default;
  span_t& operator=(span_t const&)=default;
  span_t( T* s, T* f ):b(s),e(f) {}
  span_t( T* s, std::size_t l):span_t(s, s+l) {}
};
Run Code Online (Sandbox Code Playgroud)

这是一个(实用且有用的)随机访问范围.

它的所有方法(除外operator=)都是const.你可以对它进行排序.

并非所有范围都const从范围传播到范围内的元素.

  • @akim那不是容器; 这是一个范围视图.`span`非常有用.就像使用原始C数组或缓冲区指针很有用时,`span`升级了现代C++.它允许您在缓冲区中传递范围,而无需复制缓冲区或关注缓冲区的分配方式.它为您提供了具有大量语法糖的裸机性能.它是`const`,因为它的值只是所讨论范围的范围,而不是范围的内容,比如const指针和指向const的指针是不同的.跨度的副本不会复制元素,如指针. (4认同)