Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing a union tuple in C++11

Tuples are kind of like structs. Are there also tuples that behave like unions? Or unions where I can access the members like in tuples, e.g.

my_union_tuple<int, char> u;
get<1>(u);
get<int>(u); // C++14 only, or see below

For the 2nd line, see here.

Of course, the solution should not only work for a specific union, like <int, char>, but for arbitrary types and number of types.

like image 828
Johannes Avatar asked Dec 06 '13 10:12

Johannes


1 Answers

No std::tuple<A, B> means A AND B. If you want a typesafe union-like container, have a look to boost variant.

boost::variant<int, std::string> v;

v = "hello";
std::cout << v << std::endl;

It does provide safe traversing with visitors:

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

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

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

};

Or even direct accessors that can throw if the type is not good:

std::string& str = boost::get<std::string>(v);

(Code taken from boost variant basic tutorial)

like image 51
Johan Avatar answered Nov 19 '22 04:11

Johan