There exists a way to enumerate and output all fields of any structure/class automatically, but it exists probably starting only from C++20 standard through unpacking operation (e.g. auto [a, b] = obj;
). Next code solves your task for any structure, your structure is used as example, for usage example see main()
function at the very end of code:
Try it online!
#include <iostream>
#include <tuple>
#include <type_traits>
template <auto I>
struct any_type {
template <class T> constexpr operator T &() const noexcept;
template <class T> constexpr operator T &&() const noexcept;
};
template <class T, auto... Is>
constexpr auto detect_fields_count(std::index_sequence<Is...>) noexcept {
if constexpr (requires { T{any_type<Is>{}...}; })
return sizeof...(Is);
else
return detect_fields_count<T>(std::make_index_sequence<sizeof...(Is) - 1>{});
}
template <class T>
constexpr auto fields_count() noexcept {
return detect_fields_count<T>(std::make_index_sequence<sizeof(T)>{});
}
template <class S>
constexpr auto to_tuple(S & s) noexcept {
constexpr auto count = fields_count<S>();
if constexpr (count == 8) {
auto & [f0, f1, f2, f3, f4, f5, f6, f7] = s;
return std::tie(f0, f1, f2, f3, f4, f5, f6, f7);
} else if constexpr (count == 7) {
auto & [f0, f1, f2, f3, f4, f5, f6] = s;
return std::tie(f0, f1, f2, f3, f4, f5, f6);
} else if constexpr (count == 6) {
auto & [f0, f1, f2, f3, f4, f5] = s;
return std::tie(f0, f1, f2, f3, f4, f5);
} else if constexpr (count == 5) {
auto & [f0, f1, f2, f3, f4] = s;
return std::tie(f0, f1, f2, f3, f4);
} else if constexpr (count == 4) {
auto & [f0, f1, f2, f3] = s;
return std::tie(f0, f1, f2, f3);
} else if constexpr (count == 3) {
auto & [f0, f1, f2] = s;
return std::tie(f0, f1, f2);
} else if constexpr (count == 2) {
auto & [f0, f1] = s;
return std::tie(f0, f1);
} else if constexpr (count == 1) {
auto & [f0] = s;
return std::tie(f0);
} else if constexpr (count == 0) {
return std::tie();
}
}
struct A {
int a;
int b;
char const * c;
float d;
};
int main() {
A a{.a = 1, .b = 2, .c = "c", .d = 3.14};
std::apply([](auto const &... x) {
((std::cout << x << std::endl), ...); }, to_tuple(a));
}
Output:
1
2
c
3.14