I was trying to iterate over a user-defined struct with hana::for_each
and noticed that it gets copied/moved, while Boost.Fusion
allows you to iterate on the original struct in-place.
I didn't find anything like a View
concept from Boost.Fusion
in Boost.Hana
. How do I apply transformations to sequences without copying/moving them every time?
#include <boost/hana.hpp>
#include <iostream>
struct Foo {
Foo() = default;
Foo(const Foo&) { std::cout << "copy" << std::endl; }
Foo(Foo&&) { std::cout << "move" << std::endl; }
};
struct Struct {
BOOST_HANA_DEFINE_STRUCT(Struct,
(Foo, foo)
);
};
int main() {
Struct s;
auto m = boost::hana::members(s); // copy constructor invoked
}
UPDATE: I tried to use hana::transform
to apply std::ref
to the members, but Struct
is not a Functior
, so transform
is not applicable in this case. I was able to achieve the desired behavior using hana::accessors
, but it looks a bit hacky to me. I wish there was a way to create views.
hana::for_each(hana::accessors<Struct>(), [&s](const auto& accessor) {
const auto& member = hana::second(accessor)(s); // No copying
});