'accessing std::tuple element by constexpr in type

I would like to access to a tuple element at compile time by a value constexpr in the type

#include <iostream>
#include <tuple>
#include <utility>

struct A {
    static constexpr int id = 1;
    void work() {
            std::cout << "A" << std::endl;
    }
};

struct B {
    static constexpr int id = 2;
    void work() {
            std::cout << "B" << std::endl;
    }
};

int main() {
    A a;
    B b;
    std::tuple<A,B> t = std::make_tuple(a,b);

    static constexpr int search_id = 2;

    auto& item = std::get< ? ( T::id == search_id ) ? >(t);
    item.work();
    return 0;
}

I guess using std::apply and test would be a runtime search... I'm using c++20



Solution 1:[1]

You can create constrexpr function to get index:

template <typename... Ts>
constexpr std::size_t get_index(int id)
{
    constexpr int ids[] = {Ts::id...};

    const auto it = std::find(std::begin(ids), std::end(ids), id);

    // Handle absent id.
    if (it == std::end(ids)) {
        throw std::runtime("Invalid id");
    }
    // You can also possibly handle duplicate ids.

    return std::distance(std::begin(ids), it);
}

template <int id, typename... Ts>
constexpr auto& get_item(std::tuple<Ts...>& t)
{
    return std::get<get_index<Ts...>(id)>(t);
}
template <int id, typename... Ts>
constexpr const auto& get_item(const std::tuple<Ts...>& t)
{
    return std::get<get_index<Ts...>(id)>(t);
}

and then

auto& item = get_item<search_id>(t);

Solution 2:[2]

Instead of std::get a single element, you can use std::apply to iterate over the elements of the tuple and perform operations based on the element type

A a;
B b;
auto t = std::make_tuple(a, b);
static constexpr int search_id = 2;

std::apply([](auto&... items) {
  ([]<class T>(T& item) {
    if constexpr (T::id == search_id)
      item.work();
  }(items), ...);
}, t);

Demo

If you really want to get a single tuple element with a specific id value, you can still use std::apply to expand the id of all elements and find the offset of the value equal to search_id as the template parameter of std::get

auto& item = std::apply([&t]<class... Args>(const Args&... items) -> auto& {
  constexpr auto id = [] {
    std::array ids{Args::id...};
    return ids.end() - std::ranges::find(ids, search_id);
  }();
  return std::get<id>(t);
}, t);

item.work();

Solution 3:[3]

This is a prime candidate for std::disjunction, which can be used to perform a compile-time linear search; you just need a helper type to act as the predicate:

namespace detail {
    template<typename T, auto Id, auto I, typename U = std::tuple_element_t<I, T>>
    struct get_by_id_pred : std::bool_constant<std::remove_cvref_t<U>::id == Id> {
        static constexpr auto index = I;
    };
}

template<int Id>
constexpr auto&& get_by_id(auto&& t) noexcept {
    using tuple_t = std::remove_cvref_t<decltype(t)>;
    return [&]<auto ...Is>(std::index_sequence<Is...>) -> auto&& {
        using res = std::disjunction<detail::get_by_id_pred<tuple_t, Id, Is>...>;
        static_assert(res::value, "id not found");
        return std::get<res::index>(decltype(t)(t));
    }(std::make_index_sequence<std::tuple_size_v<tuple_t>>{});
}

...

auto& item = get_by_id<search_id>(t);

Online Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jarod42
Solution 2
Solution 3