After reading this source (and also my answer) and this source, I got the impression that we can use std::source_location::function_name
to extract names of data members.
Let’s say we are given some struct_t
type with an instance of my_struct
. Further, the following properties are valid for struct_t
:
- The number of non-static data members is 3;
- The following line compiles successfully and has the expected
behavior:auto& [a,b,c] = my_struct;
; - Any additional assumptions if this is really necessary
Q: How to use C++20 without other libs and std::source_location::function_name
to extract all non-static data member names from struct_t
? The correct answer should be easily generalized to an arbitrary number of fields and also be compatible with g++, clang, and MSVC.
Proof of concept, but it is not compatible with MSVC and it looks strange:
#include <iostream>
#include <type_traits>
#include <source_location>
#include <vector>
#include <string_view>
#include <array>
struct struct_t {
int field1;
double field2;
std::vector<int> field3;
};
template<void* p>
std::string_view get(){
return std::source_location::current().function_name();
}
template<class T>
auto fields3(T&& st){
static auto inst{std::forward<T>(st)};//bad. Needs a copy or move constructor
auto& [a,b,c]=inst;
return std::array{get<(void*)&a>(), get<(void*)&b>(), get<(void*)&c>()};
}
int main()
{
for (auto field:fields3(struct_t{})){
std::cout<<field<<"n";
}
//std::string_view get() [p = &inst.field1]
//std::string_view get() [p = &inst.field2]
//std::string_view get() [p = &inst.field3]
return 0;
}
9