Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most simple tuple implementation in C++26?

C++26 is seeing some progress in making template parameter packs more ergonomic. For example P2662: Pack indexing has been accepted into the standard. With this and other related proposals, what's the most simple tuple implementation one could make?

I'm envisioning something along the lines of:

template <typename... T>
struct tuple {
    T... m;
};

tuple<int, float> tup{};
float f = tup.m[1];

Will it be possible to write something like this? If not exactly with this syntax, then how? If not at all, what proposals are missing to make this happen?

like image 807
Jan Schultke Avatar asked Oct 16 '25 19:10

Jan Schultke


1 Answers

Here you go:

#include <iostream>
#include <utility>

template <typename ...P>
auto make_my_tuple(P &&... args)
{
    return [...args = std::forward<P>(args)]<std::size_t I> -> auto &&
    {
        return args...[I];
    };
}

int main()
{
    auto t = make_my_tuple(1, 2.2f, 3.3);
    std::cout << t.operator()<1>() << '\n'; // Like `get<1>()`.
}

I'm half-joking, obviously. But you could create a template class that wraps such lambdas and gives them a decent interface.

like image 167
HolyBlackCat Avatar answered Oct 18 '25 12:10

HolyBlackCat