pfr icon indicating copy to clipboard operation
pfr copied to clipboard

Feature request: for_each_field multiple visitation

Open invexed opened this issue 4 years ago • 2 comments
trafficstars

Multiple visitation is easy enough to achieve with a library like Boost.Hana (see below), but I think it would be useful functionality for for_each_field to support directly.

template<typename Invocable, typename... Aggregates>
constexpr auto for_each_field(Invocable f, Aggregates&&... xs) -> void
{
    namespace hana = boost::hana;
    hana::for_each(hana::zip(boost::pfr::structure_tie(xs)...), hana::fuse(std::move(f)));
}

Example on Compiler Explorer

invexed avatar Feb 12 '21 11:02 invexed

boost::hana::zip_with and std::forward_as_tuple would prevent unnecessary copies occurring when constructing the inner tuples.

invexed avatar Mar 12 '21 15:03 invexed

pfr::structure_tie with parameter pack will cause an "internal compiler error" in the current latest MSVC, for those who are having this problem or don't want to use hana, the following workaround also works:

template <size_t index = 0, class ...Args>
void ForEachMultipleFields(const auto &callback, Args &&...args)
{
    callback(pfr::get<index>(args)...);

    constexpr size_t size = pfr::detail::fields_count<
        std::decay_t<std::tuple_element_t<0, std::tuple<Args...>>>
    >();
    if constexpr (index + 1 != size) {
        ForEachMultipleFields<index + 1>(callback, std::forward<Args>(args)...);
    }
}

Example

SpriteOvO avatar Jun 14 '21 22:06 SpriteOvO