std::ranges...::operator[](3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

okay so we're diving into std::ranges...::operator[](3) from the C++ Standard Libary β€” and yes, that's the manual name, spelled exactly like that in the header, no cap πŸ’…. This page is all about the default operator[] for views, and it's lowkey iconic.


πŸ’– NAME πŸ’–

std::ranges::view_interface::operator[] β€” and because the manual said it twice, we're saying it twice: std::ranges::view_interface::operator[]. It's giving "redundant but make it fashion." πŸŽ€

🌸 Synopsis 🌸

Here's the exact signature tea, verbatim with all its funky line breaks:

          template<ranges::random_access_range R = D>
          constexpr decltype(auto) operator[]( ranges::range_difference_t<R>
       (1) (since C++20)
          n );
          template<ranges::random_access_range R = const D>
          constexpr decltype(auto) operator[]( ranges::range_difference_t<R>
       (2) (since C++20)
          n ) const;

The default implementation of this operator[] member function obtains the element at the specified offset relative to the beginning iterator, and it does that by reusing the operator[] of the iterator type. Cute, very on brand. πŸ¦‹

  1. Let derived be static_cast<D&>(*this). Equivalent to return ranges::begin(derived)[n];.
  2. Same as (1), except that derived is static_cast<const D&>(*this).

πŸŽ€ Parameters πŸŽ€

  • n β€” position of the element to return. That's the whole parameter list, bestie. πŸ’…

✨ Return value ✨

The element at offset n relative to the beginning iterator. Slay. 🫢

πŸ”₯ Notes πŸ”₯

In C++20, no type derived from std::ranges::view_interface in the standard library provides their own operator[] member function. Not a single one. πŸ’€

However, these following derived types cannot use the default implementations, because they never satisfy random_access_range:

  • std::ranges::basic_istream_view
  • std::ranges::filter_view
  • std::ranges::join_view
  • std::ranges::lazy_split_view
  • std::ranges::split_view

The inherited operator[] member function is available for std::ranges::empty_view, but a call to it always results in undefined behavior.

🚨 undefined behavior alert: like, do not call it on std::ranges::empty_view. That's not a vibe check you want to fail. 😭

🌈 Example 🌈

This section is incomplete. Reason: no example. The audacity. 😭

No example yet, so we're all just out here vibing with the signatures. 🧚

⭐ Category ⭐

  • Todo no example. Yes, that's the category. It's giving "we'll get to it." πŸŽ€

Source/version check: http://cppreference.com, dated 2024.06.10, and the page is std::ranges...::operator[](3). Bye bestie, go index responsibly! πŸ’–βœ¨

πŸ“¦ where this page comes from