C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Accessing a tuple element of index not known until runtime

From: Bjorn Reese <breese_at_[hidden]>
Date: Sun, 12 Nov 2023 08:33:38 +0100
On 11/12/23 00:35, Frederick Virchanza Gotham via Std-Proposals wrote:

> I think a lot of people would agree that the best way to allow runtime
> access of tuple elements would be to use the 'visit' function. Have
> there been any other proposals to simplify runtime access of tuple
> elements?

There are two proposals that indirectly covers this. First, P0949
(Adding support for type-based metaprograming) proposes adding
mp_with_index and contains the following example

   template<class... T> void print( std::variant<T...> const& v ) {
     mp_with_index<sizeof...(T)>( v.index(), [&]( auto I ) {
         // I is mp_size_t<v.index()> here
         std::cout << std::get<I>( v ) << std::endl;
     });
   }

While the example uses std::variant, it will also work for std::tuple
and any other type with std::get support.

P0949 is stalled, but P1858 (Generalized pack declaration and usage)
demonstrates in section 4.3.3 how to implement mp_with_index.

   https://wg21.link/P0949
   https://wg21.link/P1858

Received on 2023-11-12 07:33:41