7

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.

Community
  • 1
  • 1
Johannes
  • 2,901
  • 5
  • 30
  • 50
  • 6
    These are called variants. [Boost](http://www.boost.org/doc/libs/release/libs/variant/) has an implementation of one. – Simple Dec 06 '13 at 10:21

1 Answers1

9

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)

Johan
  • 3,728
  • 16
  • 25
  • Thanks, sounds correct. From looking at the headers, I guess boost does not use variadic lists, but typelists? (the C++03 equivalent) – Johannes Dec 06 '13 at 10:28
  • @Johannes I do not know. Boost machinery is heavily dependant of the compiler and as they do support very old ones there is certainly more than one implementation. – Johan Dec 06 '13 at 10:35