pfr icon indicating copy to clipboard operation
pfr copied to clipboard

want to add `pointers to data members -> index`

Open Fuyutsubaki opened this issue 5 years ago • 2 comments
trafficstars

template<class T>
struct DelayConstruct {
	static inline T value{};  // construct in runtime.  
};
template<class T, class M>
constexpr std::size_t get_index(M T::*mem_ptr) {
	auto &t = DelayConstruct<T>::value;
	return
		std::apply([&](auto&...e) {
			int idx = 0;
			std::array<void*, sizeof...(e)> list = { (void*)&e ... };
			for (auto b : list) {
				if (b == &(t.*mem_ptr))
					return idx;
				idx += 1;
			}
			return 42;
		}, structure_tie(t));
}
//example1
struct S {
	std::string x;
	std::vector<int> y;
	std::string z;
};

static_assert(boost::pfr::get_index(&S::x) == 0);
static_assert(boost::pfr::get_index(&S::y) == 1);
static_assert(boost::pfr::get_index(&S::z) == 2);
//example2
struct S {
	static constexpr auto names = std::make_tuple("x","y","z");
	std::string x;
	std::vector<int> y;
	std::string z;
};

assert(std::string_view{"x"} == std::get<boost::pfr::get_index(&S::x)>(S::names));
assert(std::string_view{"y"} == std::get<boost::pfr::get_index(&S::y)>(S::names));
assert(std::string_view{"z"} == std::get<boost::pfr::get_index(&S::z)>(S::names));

Fuyutsubaki avatar Nov 19 '20 19:11 Fuyutsubaki

Could this be added to the library?

asfernandes avatar Apr 27 '22 19:04 asfernandes

I landed here looking for the reverse (Related: https://stackoverflow.com/questions/72889401/can-boost-pfr-be-used-to-iterate-the-fields-of-a-type-as-member-pointers) I want

template <typename T, std::size_t Index>
using ith_member_type = decltype(boost::pfr::get<Index>(std::declval<T>()));

template <typename T, std::size_t Index>
auto get_member_pointer() -> ith_member_type<T, Index> T::* {
    ???
}

BenFrantzDale avatar Aug 26 '22 14:08 BenFrantzDale