cpp-ru / ideas

Идеи по улучшению языка C++ для обсуждения
https://cpp-ru.github.io/proposals
Creative Commons Zero v1.0 Universal
90 stars 0 forks source link

Добавить operator [] на std::tuple, std::variant, std::pair #426

Closed apolukhin closed 3 years ago

apolukhin commented 3 years ago

Перенос предложения: голоса +??, -?? Автор идеи: ??

// example

std::tuple<int, double, float> my_tuple;

int first = my_tuple[ _1  ]; 
double second = my_tuple[ _2 ];
float third = my_tuple[ _3 ];

std::pair< std::string, bool > p;

std::string s = p[ _1 ] ;
bool b = p[ _2 ];
apolukhin commented 3 years ago

yndx-antoshkka, 1 апреля 2019, 13:22

Placeholders не очень удобные, лучше использовать литералы по налогии с Boost.Hana:

#include <string>
#include <tuple>

template <std::size_t I>
constexpr std::integral_constant<std::size_t, I> operator"" _c() {
    return {};
}

struct Fish { std::string name; };
struct Cat  { std::string name; };
struct Dog  { std::string name; };

auto animals = std::make_tuple(Fish{"Nemo"}, Cat{"Garfield"}, Dog{"Snoopy"});

// Access tuple elements with operator[] instead of std::get.
Cat garfield = animals[1_c];

Удалённый пользователь, 1 апреля 2019, 16:33 yndx-antoshkka,

Ну тогда, да реализация будет еще простой:

template< typename ...Args > struct tuple
{
.......

     // Вроде такого.
     template< size_t I >
   auto operator [] (  std::integral_constant<std::size_t, I> ) const { return std::get<I>(*this); }

    // и пара  перегрузок для non-const , r-value references.
};

Мне безумно не нравится использовать std::get в своем коде, потому что там сначала думать об индекс , а потом сам контайнер. В Массиве наоборот, сначала пищем контайнер, а потом сам индекс.

apolukhin commented 3 years ago

Дубликат #158