#pragma once #include "CoreTypes.h" #include "Templates/Invoke.h" #include "Templates/Utility.h" #include "Templates/TypeHash.h" #include "TypeTraits/TypeTraits.h" #include "Memory/MemoryOperator.h" #include "Miscellaneous/Compare.h" #include "Miscellaneous/AssertionMacros.h" NAMESPACE_REDCRAFT_BEGIN NAMESPACE_MODULE_BEGIN(Redcraft) NAMESPACE_MODULE_BEGIN(Utility) template requires (sizeof...(Ts) > 0 && (true && ... && CDestructible)) class TVariant; NAMESPACE_PRIVATE_BEGIN template struct TIsTVariant : FFalse { }; template struct TIsTVariant> : FTrue { }; // This class is to avoid conflicting with sizeof...(Ts) > 0 constraints when using TVariant<> in tool templates template struct TVariantProxy { }; template struct TVariantNumImpl; template struct TVariantNumImpl> : TConstant { }; template struct TVariantNumImpl> : TConstant { }; template struct TVariantNumImpl> : TConstant { }; template struct TVariantNumImpl> : TConstant { }; template struct TVariantIndexImpl; template struct TVariantIndexImpl> : TConstant>::Value + 1> { static_assert(sizeof...(Ts) != 0, "Non-existent types in variant"); }; template struct TVariantIndexImpl> : TConstant { static_assert((true && ... && !CSameAs), "Duplicate type in variant"); }; template struct TVariantIndexImpl> : TConstant { }; template struct TVariantIndexImpl> : TVariantIndexImpl> { }; template struct TVariantIndexImpl> : TVariantIndexImpl> { }; template struct TVariantIndexImpl> : TVariantIndexImpl> { }; template struct TVariantIndexImpl> : TVariantIndexImpl> { }; template struct TVariantAlternativeImpl; template struct TVariantAlternativeImpl> { static_assert(I < sizeof...(Ts) + 1, "Invalid index in variant"); using Type = TVariantAlternativeImpl>::Type; }; template struct TVariantAlternativeImpl<0, TVariantProxy> { using Type = T; }; template struct TVariantAlternativeImpl> { }; template <> struct TVariantAlternativeImpl<0, TVariantProxy<>> { }; template struct TVariantAlternativeImpl> : TVariantAlternativeImpl> { }; template struct TVariantAlternativeImpl> { using Type = TAddConst>::Type>; }; template struct TVariantAlternativeImpl> { using Type = TAddVolatile>::Type>; }; template struct TVariantAlternativeImpl> { using Type = TAddCV>::Type>; }; template struct TVariantSelectedType; template struct TVariantSelectedType { using TypeAlternativeA = TConditional, U, void>; using TypeAlternativeB = typename TVariantSelectedType::Type; using Type = TConditional, void>, TypeAlternativeB, TConditional, void>, TypeAlternativeA, TConditional, TRemoveCVRef>, TypeAlternativeB, TypeAlternativeA>>>; // 0 - Type not found // 1 - Same type found // 2 - Multiple types found // 3 - The type found static constexpr uint8 Flag = CSameAs, void> ? 0 : CSameAs, TRemoveCVRef> ? 2 : CSameAs, TRemoveCVRef< T>> ? 1 : !CSameAs, void> && !CSameAs ? 2 : 3; static constexpr bool Value = Flag & 1; }; template struct TVariantSelectedType { static constexpr uint8 Flag = 0; using Type = void; }; NAMESPACE_PRIVATE_END template concept CTVariant = NAMESPACE_PRIVATE::TIsTVariant>::Value; template inline constexpr size_t TVariantNum = NAMESPACE_PRIVATE::TVariantNumImpl::Value; template inline constexpr size_t TVariantIndex = NAMESPACE_PRIVATE::TVariantIndexImpl::Value; template using TVariantAlternative = typename NAMESPACE_PRIVATE::TVariantAlternativeImpl::Type; template requires (sizeof...(Ts) > 0 && (true && ... && CDestructible)) class TVariant { public: constexpr TVariant() : TypeIndex(0xFF) { }; constexpr TVariant(FInvalid) : TVariant() { }; constexpr TVariant(const TVariant& InValue) requires (true && ... && CTriviallyCopyConstructible) = default; constexpr TVariant(const TVariant& InValue) requires ((true && ... && CCopyConstructible) && !(true && ... && CTriviallyCopyConstructible)) : TypeIndex(static_cast(InValue.GetIndex())) { if (IsValid()) CopyConstructImpl[InValue.GetIndex()](&Value, &InValue.Value); } constexpr TVariant(TVariant&& InValue) requires (true && ... && CTriviallyMoveConstructible) = default; constexpr TVariant(TVariant&& InValue) requires ((true && ... && CMoveConstructible) && !(true && ... && CTriviallyMoveConstructible)) : TypeIndex(static_cast(InValue.GetIndex())) { if (IsValid()) MoveConstructImpl[InValue.GetIndex()](&Value, &InValue.Value); } template requires (I < sizeof...(Ts) && CConstructibleFrom>, ArgTypes...>) constexpr explicit TVariant(TInPlaceIndex, ArgTypes&&... Args) : TypeIndex(I) { using SelectedType = TVariantAlternative>; new(&Value) SelectedType(Forward(Args)...); } template requires (CConstructibleFrom) constexpr explicit TVariant(TInPlaceType, ArgTypes&&... Args) : TVariant(InPlaceIndex>>, Forward(Args)...) { } template requires (NAMESPACE_PRIVATE::TVariantSelectedType, Ts...>::Value && !CTInPlaceType> && !CTInPlaceIndex> && !CBaseOf>) constexpr TVariant(T&& InValue) : TVariant(InPlaceType, Ts...>::Type>, Forward(InValue)) { } constexpr ~TVariant() requires (true && ... && CTriviallyDestructible) = default; constexpr ~TVariant() requires (!(true && ... && CTriviallyDestructible)) { Reset(); } constexpr TVariant& operator=(const TVariant& InValue) requires (true && ... && (CTriviallyCopyConstructible && CTriviallyCopyAssignable)) = default; constexpr TVariant& operator=(const TVariant& InValue) requires ((true && ... && (CCopyConstructible && CCopyAssignable)) && !(true && ... && (CTriviallyCopyConstructible && CTriviallyCopyAssignable))) { if (&InValue == this) return *this; if (!InValue.IsValid()) { Reset(); return *this; } if (GetIndex() == InValue.GetIndex()) CopyAssignImpl[InValue.GetIndex()](&Value, &InValue.Value); else { Reset(); CopyConstructImpl[InValue.GetIndex()](&Value, &InValue.Value); TypeIndex = static_cast(InValue.GetIndex()); } return *this; } constexpr TVariant& operator=(TVariant&& InValue) requires (true && ... && (CTriviallyMoveConstructible && CTriviallyMoveAssignable)) = default; constexpr TVariant& operator=(TVariant&& InValue) requires ((true && ... && (CMoveConstructible && CMoveAssignable)) && !(true && ... && (CTriviallyMoveConstructible && CTriviallyMoveAssignable))) { if (&InValue == this) return *this; if (!InValue.IsValid()) { Reset(); return *this; } if (GetIndex() == InValue.GetIndex()) MoveAssignImpl[InValue.GetIndex()](&Value, &InValue.Value); else { Reset(); MoveConstructImpl[InValue.GetIndex()](&Value, &InValue.Value); TypeIndex = static_cast(InValue.GetIndex()); } return *this; } template requires (NAMESPACE_PRIVATE::TVariantSelectedType, Ts...>::Value) constexpr TVariant& operator=(T&& InValue) { using SelectedType = typename NAMESPACE_PRIVATE::TVariantSelectedType, Ts...>::Type; if (GetIndex() == TVariantIndex>) GetValue() = Forward(InValue); else { Reset(); new(&Value) SelectedType(Forward(InValue)); TypeIndex = TVariantIndex>; } return *this; } template requires (I < sizeof...(Ts) && CConstructibleFrom>, ArgTypes...>) constexpr TVariantAlternative>& Emplace(ArgTypes&&... Args) { Reset(); using SelectedType = TVariantAlternative>; SelectedType* Result = new(&Value) SelectedType(Forward(Args)...); TypeIndex = I; return *Result; } template requires (CConstructibleFrom) constexpr T& Emplace(ArgTypes&&... Args) { return Emplace>>(Forward(Args)...); } constexpr const type_info& GetTypeInfo() const { return IsValid() ? *TypeInfos[GetIndex()] : typeid(void); } constexpr size_t GetIndex() const { return TypeIndex != 0xFF ? TypeIndex : INDEX_NONE; } constexpr bool IsValid() const { return TypeIndex != 0xFF; } constexpr explicit operator bool() const { return TypeIndex != 0xFF; } template constexpr bool HoldsAlternative() const { return IsValid() ? GetIndex() == I : false; } template constexpr bool HoldsAlternative() const { return IsValid() ? GetIndex() == TVariantIndex> : false; } template requires (I < sizeof...(Ts)) constexpr decltype(auto) GetValue() & { checkf(HoldsAlternative(), TEXT("It is an error to call GetValue() on an wrong TVariant. Please either check HoldsAlternative() or use Get(DefaultValue) instead.")); return *reinterpret_cast< TVariantAlternative>*>(&Value); } template requires (I < sizeof...(Ts)) constexpr decltype(auto) GetValue() && { checkf(HoldsAlternative(), TEXT("It is an error to call GetValue() on an wrong TVariant. Please either check HoldsAlternative() or use Get(DefaultValue) instead.")); return MoveTemp(*reinterpret_cast< TVariantAlternative>*>(&Value)); } template requires (I < sizeof...(Ts)) constexpr decltype(auto) GetValue() const& { checkf(HoldsAlternative(), TEXT("It is an error to call GetValue() on an wrong TVariant. Please either check HoldsAlternative() or use Get(DefaultValue) instead.")); return *reinterpret_cast>*>(&Value); } template requires (I < sizeof...(Ts)) constexpr decltype(auto) GetValue() const&& { checkf(HoldsAlternative(), TEXT("It is an error to call GetValue() on an wrong TVariant. Please either check HoldsAlternative() or use Get(DefaultValue) instead.")); return MoveTemp(*reinterpret_cast>*>(&Value)); } template constexpr decltype(auto) GetValue() & { checkf(HoldsAlternative(), TEXT("It is an error to call GetValue() on an wrong TVariant. Please either check HoldsAlternative() or use Get(DefaultValue) instead.")); return *reinterpret_cast< T*>(&Value); } template constexpr decltype(auto) GetValue() && { checkf(HoldsAlternative(), TEXT("It is an error to call GetValue() on an wrong TVariant. Please either check HoldsAlternative() or use Get(DefaultValue) instead.")); return MoveTemp(*reinterpret_cast< T*>(&Value)); } template constexpr decltype(auto) GetValue() const& { checkf(HoldsAlternative(), TEXT("It is an error to call GetValue() on an wrong TVariant. Please either check HoldsAlternative() or use Get(DefaultValue) instead.")); return *reinterpret_cast(&Value); } template constexpr decltype(auto) GetValue() const&& { checkf(HoldsAlternative(), TEXT("It is an error to call GetValue() on an wrong TVariant. Please either check HoldsAlternative() or use Get(DefaultValue) instead.")); return MoveTemp(*reinterpret_cast(&Value)); } template requires (I < sizeof...(Ts)) constexpr decltype(auto) Get( TVariantAlternative>& DefaultValue) & { return HoldsAlternative() ? GetValue() : DefaultValue; } template requires (I < sizeof...(Ts)) constexpr decltype(auto) Get(const TVariantAlternative>& DefaultValue) const& { return HoldsAlternative() ? GetValue() : DefaultValue; } template constexpr decltype(auto) Get( T& DefaultValue) & { return HoldsAlternative() ? GetValue() : DefaultValue; } template constexpr decltype(auto) Get(const T& DefaultValue) const& { return HoldsAlternative() ? GetValue() : DefaultValue; } template requires (true && ... && CInvocable) FORCEINLINE decltype(auto) Visit(F&& Func) & { checkf(IsValid(), TEXT("It is an error to call Visit() on an wrong TVariant. Please either check IsValid().")); using ReturnType = TCommonType...>; using FInvokeImpl = ReturnType(*)(F&&, void*); static constexpr FInvokeImpl InvokeImpl[] = { [](F&& Func, void* This) -> ReturnType { return InvokeResult(Forward(Func), *reinterpret_cast(This)); }... }; return InvokeImpl[GetIndex()](Forward(Func), &Value); } template requires (true && ... && CInvocable) FORCEINLINE decltype(auto) Visit(F&& Func) && { checkf(IsValid(), TEXT("It is an error to call Visit() on an wrong TVariant. Please either check IsValid().")); using ReturnType = TCommonType...>; using FInvokeImpl = ReturnType(*)(F&&, void*); static constexpr FInvokeImpl InvokeImpl[] = { [](F&& Func, void* This) -> ReturnType { return InvokeResult(Forward(Func), MoveTemp(*reinterpret_cast(This))); }... }; return InvokeImpl[GetIndex()](Forward(Func), &Value); } template requires (true && ... && CInvocable) FORCEINLINE decltype(auto) Visit(F&& Func) const& { checkf(IsValid(), TEXT("It is an error to call Visit() on an wrong TVariant. Please either check IsValid().")); using ReturnType = TCommonType...>; using FInvokeImpl = ReturnType(*)(F&&, const void*); static constexpr FInvokeImpl InvokeImpl[] = { [](F&& Func, const void* This) -> ReturnType { return InvokeResult(Forward(Func), *reinterpret_cast(This)); }... }; return InvokeImpl[GetIndex()](Forward(Func), &Value); } template requires (true && ... && CInvocable) FORCEINLINE decltype(auto) Visit(F&& Func) const&& { checkf(IsValid(), TEXT("It is an error to call Visit() on an wrong TVariant. Please either check IsValid().")); using ReturnType = TCommonType...>; using FInvokeImpl = ReturnType(*)(F&&, const void*); static constexpr FInvokeImpl InvokeImpl[] = { [](F&& Func, const void* This) -> ReturnType { return InvokeResult(Forward(Func), MoveTemp(*reinterpret_cast(This))); }... }; return InvokeImpl[GetIndex()](Forward(Func), &Value); } template requires (true && ... && CInvocableResult) FORCEINLINE R Visit(F&& Func) & { return Visit(Forward(Func)); } template requires (true && ... && CInvocableResult) FORCEINLINE R Visit(F&& Func) && { return MoveTemp(*this).Visit(Forward(Func)); } template requires (true && ... && CInvocableResult) FORCEINLINE R Visit(F&& Func) const& { return Visit(Forward(Func)); } template requires (true && ... && CInvocableResult) FORCEINLINE R Visit(F&& Func) const&& { return MoveTemp(*this).Visit(Forward(Func)); } constexpr void Reset() { if (GetIndex() == INDEX_NONE) return; if constexpr (!(true && ... && CTriviallyDestructible)) { DestroyImpl[GetIndex()](&Value); } TypeIndex = static_cast(INDEX_NONE); } constexpr size_t GetTypeHash() const requires (true && ... && CHashable) { if (!IsValid()) return 114514; using NAMESPACE_REDCRAFT::GetTypeHash; using FHashImpl = size_t(*)(const void*); constexpr FHashImpl HashImpl[] = { [](const void* This) -> size_t { return GetTypeHash(*reinterpret_cast(This)); }... }; return HashCombine(GetTypeHash(GetIndex()), HashImpl[GetIndex()](&Value)); } constexpr void Swap(TVariant& InValue) requires (true && ... && (CMoveConstructible && CSwappable)) { if (!IsValid() && !InValue.IsValid()) return; if (IsValid() && !InValue.IsValid()) { InValue = MoveTemp(*this); Reset(); return; } if (InValue.IsValid() && !IsValid()) { *this = MoveTemp(InValue); InValue.Reset(); return; } if (GetIndex() == InValue.GetIndex()) { using NAMESPACE_REDCRAFT::Swap; using FSwapImpl = void(*)(void*, void*); constexpr FSwapImpl SwapImpl[] = { [](void* A, void* B) { Swap(*reinterpret_cast(A), *reinterpret_cast(B)); }... }; SwapImpl[GetIndex()](&Value, &InValue.Value); return; } TVariant Temp = MoveTemp(*this); *this = MoveTemp(InValue); InValue = MoveTemp(Temp); } private: static constexpr const type_info* TypeInfos[] = { &typeid(Ts)... }; using FCopyConstructImpl = void(*)(void*, const void*); using FMoveConstructImpl = void(*)(void*, void*); using FCopyAssignImpl = void(*)(void*, const void*); using FMoveAssignImpl = void(*)(void*, void*); using FDestroyImpl = void(*)(void* ); static constexpr FCopyConstructImpl CopyConstructImpl[] = { [](void* A, const void* B) { if constexpr (requires(Ts* A, const Ts* B) { Memory::CopyConstruct (A, B); }) Memory::CopyConstruct (reinterpret_cast(A), reinterpret_cast(B)); else checkf(false, TEXT("The type '%s' is not copy constructible."), typeid(Ts).name()); }... }; static constexpr FMoveConstructImpl MoveConstructImpl[] = { [](void* A, void* B) { if constexpr (requires(Ts* A, Ts* B) { Memory::MoveConstruct (A, B); }) Memory::MoveConstruct (reinterpret_cast(A), reinterpret_cast< Ts*>(B)); else checkf(false, TEXT("The type '%s' is not move constructible."), typeid(Ts).name()); }... }; static constexpr FCopyAssignImpl CopyAssignImpl[] = { [](void* A, const void* B) { if constexpr (requires(Ts* A, const Ts* B) { Memory::CopyAssign (A, B); }) Memory::CopyAssign (reinterpret_cast(A), reinterpret_cast(B)); else checkf(false, TEXT("The type '%s' is not copy assignable."), typeid(Ts).name()); }... }; static constexpr FMoveAssignImpl MoveAssignImpl[] = { [](void* A, void* B) { if constexpr (requires(Ts* A, Ts* B) { Memory::MoveAssign (A, B); }) Memory::MoveAssign (reinterpret_cast(A), reinterpret_cast< Ts*>(B)); else checkf(false, TEXT("The type '%s' is not move assignable."), typeid(Ts).name()); }... }; static constexpr FDestroyImpl DestroyImpl[] = { [](void* A ) { if constexpr (requires(Ts* A ) { Memory::Destruct (A ); }) Memory::Destruct (reinterpret_cast(A) ); else checkf(false, TEXT("The type '%s' is not destructible."), typeid(Ts).name()); }... }; TAlignedUnion<1, Ts...> Value; uint8 TypeIndex; friend constexpr bool operator==(const TVariant& LHS, const TVariant& RHS) requires (true && ... && CEqualityComparable) { if (LHS.GetIndex() != RHS.GetIndex()) return false; if (LHS.IsValid() == false) return true; using FCompareImpl = bool(*)(const void*, const void*); constexpr FCompareImpl CompareImpl[] = { [](const void* LHS, const void* RHS) -> bool { return *reinterpret_cast(LHS) == *reinterpret_cast(RHS); }... }; return CompareImpl[LHS.GetIndex()](&LHS.Value, &RHS.Value); } friend constexpr partial_ordering operator<=>(const TVariant& LHS, const TVariant& RHS) requires (true && ... && CSynthThreeWayComparable) { if (LHS.GetIndex() != RHS.GetIndex()) return partial_ordering::unordered; if (LHS.IsValid() == false) return partial_ordering::equivalent; using FCompareImpl = partial_ordering(*)(const void*, const void*); constexpr FCompareImpl CompareImpl[] = { [](const void* LHS, const void* RHS) -> partial_ordering { return SynthThreeWayCompare(*reinterpret_cast(LHS), *reinterpret_cast(RHS)); }...}; return CompareImpl[LHS.GetIndex()](&LHS.Value, &RHS.Value); } }; template requires (!CBaseOf, T> && CEqualityComparable) constexpr bool operator==(const TVariant& LHS, const T& RHS) { return LHS.template HoldsAlternative() ? LHS.template GetValue() == RHS : false; } template constexpr bool operator==(const TVariant& LHS, FInvalid) { return !LHS.IsValid(); } NAMESPACE_MODULE_END(Utility) NAMESPACE_MODULE_END(Redcraft) NAMESPACE_REDCRAFT_END