#ifndef QT_EITHER_H #define QT_EITHER_H #include #include #include template struct EitherHelper { }; template struct EitherHelper { EitherHelper(const QVariant& _value) : value(_value) {} bool is() const { return value.userType() == qMetaTypeId(); } T1 as() const { return value.value(); } const QVariant& value; }; template struct EitherHelper { EitherHelper(const QVariant& _value) : value(_value) {} bool is() const { return value.userType() == qMetaTypeId(); } T2 as() const { return value.value(); } const QVariant& value; }; /** A sum type which represents either an instance of T1 or * an instance of T2. * * Either uses QVariant for the underlying storage, so the * same performance considerations apply. An Either instance * has the same size as a QVariant (12 bytes) regardless of the * types used. * * A convenient way to create an Either instance is * the some(T) function which returns a type that can be implicitly * cast to any Either<> type where T1 or T2 is T. */ template class Either { public: Either(const T1& t1) : m_value(QVariant::fromValue(t1)) { } Either(const T2& t2) : m_value(QVariant::fromValue(t2)) { } template bool is() const; template T as() const; bool is1st() const; bool is2nd() const; T1 as1st() const; T2 as2nd() const; private: template EitherHelper is_t() const; QVariant m_value; }; template template EitherHelper Either::is_t() const { return EitherHelper(m_value); } template template bool Either::is() const { return is_t().is(); } template template T Either::as() const { Q_ASSERT_X(is(),"Either::as()","Tried to extract the wrong type from an Either instance"); return is_t().as(); } template bool Either::is1st() const { return is(); } template bool Either::is2nd() const { return is(); } template T1 Either::as1st() const { return as(); } template T2 Either::as2nd() const { return as(); } template struct MakeEither { MakeEither(const T1& _value) : value(_value) {} template operator Either() { return Either(value); } template operator Either() { return Either(value); } const T1& value; }; template inline MakeEither some(const T1& value) { return MakeEither(value); } #endif