Matias Chara
Matias Chara

Reputation: 981

Returning the active member of a union using a function within it

or within its outer struct/class if anonymously nested. (<- to add to the title without making it longer).

I want to be able to simply call a function and get the member of a union being used (by any means, e.g returning it, modifying a parameter etc...), not the type (or an identifier for the type) but the actual member , or a non-void pointer to it. Is there a way to do this in modern (c++14) c++?

Upvotes: 3

Views: 229

Answers (1)

Jarod42
Jarod42

Reputation: 217235

With boost::variant, the current value/type is stored. You may apply a static_visitor to the variant as for example:

#include "boost/variant.hpp"
#include <iostream>

class times_two_visitor : public boost::static_visitor<>
{
public:

    void operator()(int & i) const
    {
        i *= 2;
    }

    void operator()(std::string & str) const
    {
        str += str;
    }
};


int main()
{
    boost::variant<int, std::string> u("hello world");
    std::cout << u; // output: hello world

    boost::apply_visitor(times_two_visitor(), u);
    std::cout << u; // output: hello worldhello world
    u = 21;
    boost::apply_visitor(times_two_visitor(), u);
    std::cout << u; // output: 42
}

Upvotes: 1

Related Questions