Topic: Ideas for extending std::tuple with field-name based access


Author: "'Johannes Schaub' via ISO C++ Standard - Future Proposals" <std-proposals@isocpp.org>
Date: Wed, 12 Oct 2016 13:48:16 +0200
Raw View
Hello all,

Using type-tags to access tuple fields is a common technique to access
fields by "name"

    struct position_tag : type<double> { };
    struct color_tag : type<QColor> { };

    my_tuple<field<position_tag, color_tag> m;

    QColor c1 = std::get<color_tag>(m);
    QColor c2 = std::get<QColor>(m);
    QColor c3 = std::get<1>(m);

I was thinking about extending std::tuple with support for tags. This
can be done (i believe) most straight forward with string template
arguments, if we would have support for them in the future

    std::tuple<field<double, "position">, field<QColor, "color">> getStop();

    auto m = getStop();
    double pos = std::get<"position">(m);

An alternative (but uglier) implementation would abuse unnamed struct
definitions in template-arguments with the "type" baseclass of above
to communicate the type

    std::tuple<struct : typed<double> { type position; },
                     struct : typed<QColor> { type color; }> getStop();

Here, "type" is declared in base-class "typed" as a type-alias for its
template-parameter. When tuple sees a parameter has "typed<T>" as a
base class, it inherits from it. Therefore you could write

    auto m = getStop();
    QColor c = m.color;

std::get<N> would cast the unnamed-struct to "struct_type::type",
requiring a standard-layout struct (can be tested-for with a
type-trait). So the unnamed-struct cannot "escape" to the users of the
tuple.

What do you think about the two approaches? Are there existing papers
about perhaps other techniques?

--
You received this message because you are subscribed to the Google Groups "ISO C++ Standard - Future Proposals" group.
To unsubscribe from this group and stop receiving emails from it, send an email to std-proposals+unsubscribe@isocpp.org.
To post to this group, send email to std-proposals@isocpp.org.
To view this discussion on the web visit https://groups.google.com/a/isocpp.org/d/msgid/std-proposals/CANu6V4VcQQxjb0LvEVjAeNkZ892Gn32cirgVwfjYuAJkkR5EPA%40mail.gmail.com.

.