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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With