문제

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top