How can I map nested structure data with std::views::transform
?
In the code below the transformation for as_v1
works just fine and allows copying the data.
How can I do the same for the data in the nested structure NS?
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
struct S
{
float v1;
float v2;
struct SN {
float v3;
};
SN sn;
};
int main() {
std::vector<S> aos{ { 1.0f, 2.0f, { 3.0f } } };
std::vector<float> soa(aos.size());
// Would work just fine for the:
// auto as_v1 = aos | std::views::transform(&S::v1);
// How could I manage a nested structure's member:
// This, of course, doesn't compile because of types inconsistency
auto as_v3 = aos | std::views::transform(offsetof(S, sn.v3));
std::ranges::copy(as_v3, soa.begin());
std::cout << "soa value:" << soa[0] << std::endl;
}
I understand that S::SN::v3 won't work since we need the offset of the member and it will be relative to the sn
object and it seems that offsetof
should do the job, but I can't figure out how to make type conversion.
Is is doable?
You are trying to access the member of a member.
This will do it.
auto as_v3 = aos | std::views::transform(&S::sn) | std::views::transform(&S::SN::v3);