'Struct member names as map keys

I'm looking for a way to map a struct's member to a string (or some other type for that matter):

struct Foo
{
    int intMember;
    int otherIntMember;
    char charMember;
    std::optional<int> optIntMember;
};

std::map<???, std::string> myMap = {
    {Foo::intMember, "IntMemberName"},
    {Foo::otherIntMember, "OtherIntMemberName"},
    {Foo::charMember, "CharMemberName"},
    {Foo::optIntMember, "OptIntMemberName"}
};

void myFunc()
{
    std::cout << myMap[Foo::intMember] << std::endl;
    std::cout << myMap[Foo::otherintMember] << std::endl;
    std::cout << myMap[Foo::charMember] << std::endl;
    std::cout << myMap[Foo::optIntMember] << std::endl;
}

One possible approach I've seen so far is using offsetof to map offsets to strings (which looks like a way outdated and bug-prone function). Having an enum for each of the members might also be an option but that honestly feels bulky and like an overkill.

Is there a simple elegant way to achieve this in modern C++?

c++


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source