Is it possible to use ranges adaptors to revert the projected member to the original class object?

Viewed 67

C++20 brings a very powerful projection utility. Some range adaptors such as transform_view and elements_view allow us to easily project operations to the member variable of the origin class object (godbolt):

auto historical_figures = vector{
    pair{"Lovelace"sv, 1815},
    {"Turing"sv, 1912},
    {"Babbage"sv, 1791},
    {"Hamilton"sv, 1936}
};

// view of ints
auto birth_years = historical_figures
                 | views::transform(&pair<string_view, int>::second);

But can we reproject the projected member variable back to the original class object? For example:

// views of pair<string_view, int>
auto origin_figures = historical_figures
                    | views::transform(&pair<string_view, int>::second)
                    | views::reproject<pair<string_view, int>>; 

The reason I ask this is that the projection function is a member object pointer of type int pair<string_view, int>::*, which seems to save the type information of the projected class, so it may have some potential conversion relationship with the original object.

Is this theoretically feasible? If possible, can we use ranges adaptors to construct this reprojection? If it is not possible, is it possible to just reproject std::pair?

1 Answers

It’s not in general possible to identify an object based on the identity of one of its subobjects, even if you know which subobject it is rather than just its type (which might leave multiple possibilities). The pointer arithmetic model just doesn’t allow it, partly because it allows certain aliasing optimizations when the compiler can see that one object isn’t “reachable” from another.

Related