Building a federated tuple in C ++ 11

Tuples are similar structures . Are there also tuples that behave like unions? Or unions, where I can access members, for example, in tuples, for example

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

For the second line, see here .

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

+6
source share
1 answer

No std::tuple<A, B> means A AND B. If you want to create a typical merged container, look at the boost option .

 boost::variant<int, std::string> v; v = "hello"; std::cout << v << std::endl; 

It provides safe movement of 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 suitable:

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

(Code taken from basic acceleration tutorial )

+8
source

Source: https://habr.com/ru/post/959461/


All Articles