C++ Logo

std-proposals

Advanced search

Re: [std-proposals] C-style array specialization for std::get

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Tue, 1 Mar 2022 10:58:43 -0500
On Tue, Mar 1, 2022 at 10:13 AM Nikolay Mihaylov via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Once again, why do we need the size?
> Shall we check the size?
> Via static_assert?
> During runtime?
>

In the proposed std::get for C arrays, AIUI, the size would be part of the
signature. It would look like this:

template<size_t X, class T, size_t N> requires (X < N)
constexpr T& get(T (&arr)[N]) noexcept {
    return arr[X];
}
template<size_t X, class T, size_t N> requires (X < N)
constexpr T&& get(T (&&arr)[N]) noexcept {
    return std::move(arr[X]);
}
template<size_t X, class T, size_t N> requires (X < N)
constexpr const T& get(const T (&arr)[N]) noexcept {
    return arr[X];
}
template<size_t X, class T, size_t N> requires (X < N)
constexpr const T&& get(const T (&&arr)[N]) noexcept {
    return std::move(arr[X]);
}

and then you could do things like

    void f(auto& t) requires requires { std::get<1>(t); } { puts("yes"); }
    void f(auto&) { puts("no"); }
    int main() {
      std::tuple<int> t; std::tuple<int, int> u; f(t); f(u); // prints "no
yes"
      int a[1]; int b[2]; f(a); f(b); // prints "no yes"
    }

–Arthur

Received on 2022-03-01 15:58:54