简体   繁体   中英

How to get the member name of specific element using boost fusion

I'm using boost fusion library to literate through all members in a struct. I believe that boost::fusion::extension::struct_member_name<MembersList, Index::value>::call() is already giving the member name. But is there a way to get the name outside of this structure without the need to pass another parameter to the function other than member_value?

template <typename MembersList>
struct Struct
{
    Struct(const MembersList& members) : mMembers(members)
    {
    }

    template <typename Index>
    void operator() (Index idx) const
    {
        std::string field_name = boost::fusion::extension::struct_member_name<MembersList, Index::value>::call();
        const auto& member_value = boost::fusion::at<Index>(mMembers);

        getName(member_value); // function that returns the name of member_value
    }
};

Let's say the struct we are processing is defined as below and I could like to have the getName function to return a string of either 'name' or 'value'.

BOOST_FUSION_DEFINE_STRUCT(
    (NameSpace),
    Members,
    (string, name)
    (int, value)
    )

Edit:

Is there a way I could set up the structure so I can access the field_name variable outside? Maybe have something like

template <typename MembersList>
struct Struct
{
    std::string field_name;

    template <typename Index>
    void operator() (Index idx) const
    {
        field_name = boost::fusion::extension::struct_member_name<MembersList, Index::value>::call();
    }

    std::string getName(){
        return field_name;
    }
};

void someFunction() {
    std::string name = getName();
}

But in the right format?

Thanks!

There is no such way

A member object is just an object. Once you pass it along it's just an int& or a std::string& . There is zero context to deduce it is actually a member of a different object.

Of course, iff you know the enclosing object you can iterate all fusion-adapted members and compare the addresses to the address of the subobject member_value I'm not sure why you'd want that, but there you go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM