I have some tricky code that I need to initialize many objects that refer to each other. I want to allocate and construct them all at once, so I put them all in a struct.
It looks like this:
// User code struct level1 { explicit constexpr level1(int* ptr) : ptr{ptr} {} int* ptr; }; struct level2 { constexpr level2(int* ptr_0, level1* ptr_1) : ptr_0{ptr_0}, ptr_1{ptr_1} {} int* ptr_0; level1* ptr_1; }; struct level3 { constexpr level3(int* ptr_0, level1* ptr_1, level2* ptr_2) : ptr_0{ptr_0}, ptr_1{ptr_1}, ptr_2{ptr_2} {} int* ptr_0; level1* ptr_1; level2* ptr_2; }; // Library side struct self_referential { explicit constexpr self_referential(int base_value) : a{base_value}, b{&a}, c{&a, &b}, d{&a, &b, &c} {} int a; level1 b; level2 c; level3 d; }; constexpr auto eval_result() -> int { auto const s = self_referential{9}; return *s.d.ptr_2->ptr_1->ptr; } auto main() -> int { return eval_result(); } This code is valid and runs: https://godbolt.org/z/sMqofdshY
Now the problem, is that I want to make self_referential a variadic template. Is there a way I can make this struct generic? I cannot change the definition of levelx as they are user side, I want to send levelx to self referential as a variadic template.
I tried with a tuple at first:
template<typename Base, typename... Ts> struct self_referential { explicit constexpr self_referential(Base b) : values{b, std::get<???>(values)...} {} std::tuple<Base, Ts...> values; }; I think I'm kinda breaking std::get's contract here. Also, I would kinda need a pack of pack.
I tried using inheritance, but again without much luck:
template<typename Base, typename... Ts> struct self_referential : self_referential<Ts...> { explicit constexpr self_referential(Base base) : self_referential<Ts...>{&b}, b{base} {} // oh no Base b; }; It looked easy at first but then I realized I don't have references to all the other b in the struct. On top of that, parents are initialized before child classes so this won't really work either.
Is there an easier way to do that? Maybe some kind of reverse of what I was doing with the inheritance?