7

Otherwise, size(t) converted to its decayed type, if ranges::disable_sized_range<std::remove_cv_t<T>> is false, and the converted expression is valid and has an integer-like type, where the overload resolution is performed with the following candidates:

  • void size(auto&) = delete;
  • void size(const auto&) = delete; 1
class Test {
    friend size_t size(/*const*/ Test&) {
        return 0;
    }
};

int main() {
    std::ranges::size(Test{});
    // no matching function error when adding the `const` qualifier
}

https://godbolt.org/z/79e5vrKrT


Generally, size method doesn't require to modify the range, like what std::size does.

Why is there such a constraint of std::ranges::size? (Seems it's only performed for non-member version.)

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
zjyhjqs
  • 609
  • 4
  • 11

1 Answers1

3

Why is there such a constraint of std::ranges::size? (Seems it's only performed for non-member version.)

Although the size method does not modify the range, some ranges do not have a const-qualified member begin(), which allows only non-const-qualified objects to model a range.

This also makes some range adaptors in the standard may only have a non-const-qualified size.

For your example, considering that Test only has non-const begin/end or size, then friend size_t size(Test&) can really only be the option.

康桓瑋
  • 33,481
  • 5
  • 40
  • 90
  • 2
    But it's surprising that `friend size_t size(const Test&)` doesn't work for both const and non-const objects. It only doesn't work for both because of the`void size(auto&) = delete;` overload, if that is removed from the implementation, then it works. – Jonathan Wakely Jun 08 '22 at 17:33
  • @JonathanWakely Agree. This seems more like a standard defect to me. – 康桓瑋 Jun 08 '22 at 17:45
  • 2
    We had [LWG 3480](https://cplusplus.github.io/LWG/issue3480), which is also based on these poison pills, which we resolved by changing the non-member functions -- but that one could've also been resolved by changing the poison pills. – Barry Jun 08 '22 at 17:47
  • 1
    Hum, I think removing this non-`const` size poison pill would be a more appropriate solution here since I don't see any observable reasonable harm from removing it. – 康桓瑋 Jun 08 '22 at 18:05