How to get the field names with source_location::function_name

  Kiến thức lập trình

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 field names.

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:

  1. The number of non-static fields is 3;
  2. The following line compiles successfully and has the expected
    behavior:auto& [a,b,c] = my_struct;;
  3. 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 field names from strcut_t? The correct answer should be easily generalized to an arbitrary number of fields and also be compatible with g++, clang and mvsc compilers.

Proof on 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>

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>
std::array<std::string_view, 3> fields3(T&& st){
    static auto inst{std::forward<T>(st)};//bad. Needs a copy or move constructor 
    auto& [a,b,c]=inst;
    return {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;
}

LEAVE A COMMENT