#pragma once #include "CoreTypes.h" #include "Templates/Invoke.h" #include "Templates/Utility.h" #include "Templates/TypeHash.h" #include "TypeTraits/TypeTraits.h" #include "Templates/Meta.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 { }; template struct TVariantNumImpl; template struct TVariantNumImpl> : TConstant>> { }; template struct TVariantIndexImpl; template struct TVariantIndexImpl> : TConstant>> { }; template struct TVariantAlternativeImpl; template struct TVariantAlternativeImpl> { using Type = Meta::TType>; }; template struct TVariantOverloadType { using FrontType = Meta::TFront; using NextSequence = Meta::TPop; using NextUniqueSequence = typename TVariantOverloadType::Type; // T_i x[] = { Forward(t) }; static constexpr bool bConditional = requires { DeclVal()({ DeclVal() }); }; using Type = TConditional, NextUniqueSequence>; }; template struct TVariantOverloadType> { using Type = TTypeSequence<>; }; template using TVariantSelectedType = Meta::TOverloadResolution>::Type>; 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 = TCopyCV>::Type>; template requires (sizeof...(Ts) > 0 && (true && ... && CDestructible)) class TVariant { public: FORCEINLINE constexpr TVariant() : TypeIndex(0xFF) { }; FORCEINLINE constexpr TVariant(FInvalid) : TVariant() { }; FORCEINLINE constexpr TVariant(const TVariant& InValue) requires (true && ... && CTriviallyCopyConstructible) = default; FORCEINLINE constexpr TVariant(const TVariant& InValue) requires ((true && ... && CCopyConstructible) && !(true && ... && CTriviallyCopyConstructible)) : TypeIndex(static_cast(InValue.GetIndex())) { if (IsValid()) CopyConstructImpl[InValue.GetIndex()](&Value, &InValue.Value); } FORCEINLINE constexpr TVariant(TVariant&& InValue) requires (true && ... && CTriviallyMoveConstructible) = default; FORCEINLINE 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...>) FORCEINLINE constexpr explicit TVariant(TInPlaceIndex, ArgTypes&&... Args) : TypeIndex(I) { using SelectedType = TVariantAlternative>; new (&Value) SelectedType(Forward(Args)...); } template requires (CConstructibleFrom) FORCEINLINE constexpr explicit TVariant(TInPlaceType, ArgTypes&&... Args) : TVariant(InPlaceIndex>>, Forward(Args)...) { } template requires (requires { typename NAMESPACE_PRIVATE::TVariantSelectedType; } && !CTInPlaceType> && !CTInPlaceIndex> && !CBaseOf>) FORCEINLINE constexpr TVariant(T&& InValue) : TVariant(InPlaceType>, Forward(InValue)) { } FORCEINLINE constexpr ~TVariant() requires (true && ... && CTriviallyDestructible) = default; FORCEINLINE constexpr ~TVariant() requires (!(true && ... && CTriviallyDestructible)) { Reset(); } FORCEINLINE 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; } FORCEINLINE 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 (requires { typename NAMESPACE_PRIVATE::TVariantSelectedType; }) FORCEINLINE constexpr TVariant& operator=(T&& InValue) { using SelectedType = NAMESPACE_PRIVATE::TVariantSelectedType; if (GetIndex() == TVariantIndex>) GetValue() = Forward(InValue); else { Reset(); new (&Value) SelectedType(Forward(InValue)); TypeIndex = TVariantIndex>; } return *this; } 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 && CEqualityComparable) FORCEINLINE constexpr bool operator==(const T& InValue) const& { return HoldsAlternative() ? GetValue() == InValue : false; } template requires (!CBaseOf && CEqualityComparable) FORCEINLINE constexpr partial_ordering operator<=>(const T& InValue) const& { return HoldsAlternative() ? SynthThreeWayCompare(GetValue(), InValue) : partial_ordering::unordered; } FORCEINLINE constexpr bool operator==(FInvalid) const& { return !IsValid(); } template requires (I < sizeof...(Ts) && CConstructibleFrom>, ArgTypes...>) FORCEINLINE constexpr TVariantAlternative>& Emplace(ArgTypes&&... Args) { Reset(); using SelectedType = TVariantAlternative>; SelectedType* Result = new (&Value) SelectedType(Forward(Args)...); TypeIndex = I; return *Result; } template requires (CConstructibleFrom) FORCEINLINE constexpr T& Emplace(ArgTypes&&... Args) { return Emplace>>(Forward(Args)...); } FORCEINLINE constexpr const type_info& GetTypeInfo() const { return IsValid() ? *TypeInfos[GetIndex()] : typeid(void); } FORCEINLINE constexpr size_t GetIndex() const { return TypeIndex != 0xFF ? TypeIndex : INDEX_NONE; } FORCEINLINE constexpr bool IsValid() const { return TypeIndex != 0xFF; } FORCEINLINE constexpr explicit operator bool() const { return TypeIndex != 0xFF; } template FORCEINLINE constexpr bool HoldsAlternative() const { return IsValid() ? GetIndex() == I : false; } template FORCEINLINE constexpr bool HoldsAlternative() const { return IsValid() ? GetIndex() == TVariantIndex> : false; } template requires (I < sizeof...(Ts)) FORCEINLINE 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)) FORCEINLINE 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)) FORCEINLINE 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)) FORCEINLINE 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 FORCEINLINE 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 FORCEINLINE 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 FORCEINLINE 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 FORCEINLINE 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)) FORCEINLINE constexpr decltype(auto) Get( TVariantAlternative>& DefaultValue) & { return HoldsAlternative() ? GetValue() : DefaultValue; } template requires (I < sizeof...(Ts)) FORCEINLINE constexpr decltype(auto) Get(const TVariantAlternative>& DefaultValue) const& { return HoldsAlternative() ? GetValue() : DefaultValue; } template FORCEINLINE constexpr decltype(auto) Get( T& DefaultValue) & { return HoldsAlternative() ? GetValue() : DefaultValue; } template FORCEINLINE constexpr decltype(auto) Get(const T& DefaultValue) const& { return HoldsAlternative() ? GetValue() : DefaultValue; } FORCEINLINE constexpr void Reset() { if (GetIndex() == INDEX_NONE) return; if constexpr (!(true && ... && CTriviallyDestructible)) { DestroyImpl[GetIndex()](&Value); } TypeIndex = static_cast(INDEX_NONE); } FORCEINLINE 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; }; NAMESPACE_PRIVATE_BEGIN template struct TVariantVisitImpl { struct GetTotalNum { FORCEINLINE static constexpr size_t Do() { if (sizeof...(VariantTypes) == 0) return 0; constexpr size_t VariantNums[] = { TVariantNum>... }; size_t Result = 1; for (size_t Index = 0; Index < sizeof...(VariantTypes); ++Index) { Result *= VariantNums[Index]; } return Result; }; }; struct EncodeIndices { FORCEINLINE static constexpr size_t Do(initializer_list Indices) { constexpr size_t VariantNums[] = { TVariantNum>... }; size_t Result = 0; for (size_t Index = 0; Index < sizeof...(VariantTypes); ++Index) { Result *= VariantNums[Index]; Result += GetData(Indices)[Index]; } return Result; }; }; struct DecodeExtent { FORCEINLINE static constexpr size_t Do(size_t EncodedIndex, size_t Extent) { constexpr size_t VariantNums[] = { TVariantNum>... }; for (size_t Index = Extent + 1; Index < sizeof...(VariantTypes); ++Index) { EncodedIndex /= VariantNums[Index]; } return EncodedIndex % VariantNums[Extent]; }; }; template struct InvokeEncoded; template struct InvokeEncoded> { FORCEINLINE static constexpr decltype(auto) Do(F&& Func, VariantTypes&&... Variants) { return Invoke(Forward(Func), Forward(Variants).template GetValue()...); } template struct Result { FORCEINLINE static constexpr Ret Do(F&& Func, VariantTypes&&... Variants) { return InvokeResult(Forward(Func), Forward(Variants).template GetValue()...); } }; }; template struct InvokeVariant; template struct InvokeVariant> { FORCEINLINE static constexpr decltype(auto) Do(F&& Func, VariantTypes&&... Variants) { using ExtentIndices = TIndexSequenceFor; using ResultType = TCommonType::Do(Forward(Func), Forward(Variants)...))...>; using InvokeImplType = ResultType(*)(F&&, VariantTypes&&...); constexpr InvokeImplType InvokeImpl[] = { InvokeEncoded::template Result::Do... }; return InvokeImpl[EncodeIndices::Do({ Variants.GetIndex()... })](Forward(Func), Forward(Variants)...); } template struct Result { FORCEINLINE static constexpr Ret Do(F&& Func, VariantTypes&&... Variants) { using ExtentIndices = TIndexSequenceFor; using InvokeImplType = Ret(*)(F&&, VariantTypes&&...); constexpr InvokeImplType InvokeImpl[] = { InvokeEncoded::template Result::Do... }; return InvokeImpl[EncodeIndices::Do({ Variants.GetIndex()... })](Forward(Func), Forward(Variants)...); } }; }; FORCEINLINE static constexpr decltype(auto) Do(F&& Func, VariantTypes&&... Variants) { return InvokeVariant>::Do(Forward(Func), Forward(Variants)...); } template struct Result { FORCEINLINE static constexpr Ret Do(F&& Func, VariantTypes&&... Variants) { return InvokeVariant>::template Result::Do(Forward(Func), Forward(Variants)...); } }; }; NAMESPACE_PRIVATE_END template requires (CTVariant> && (true && ... && CTVariant>)) constexpr decltype(auto) Visit(F&& Func, FirstVariantType&& FirstVariant, VariantTypes&&... Variants) { checkf((true && ... && Variants.IsValid()), TEXT("It is an error to call Visit() on an wrong TVariant. Please either check IsValid().")); return NAMESPACE_PRIVATE::TVariantVisitImpl::Do(Forward(Func), Forward(FirstVariant), Forward(Variants)...); } template requires (CTVariant> && (true && ... && CTVariant>)) constexpr Ret Visit(F&& Func, FirstVariantType&& FirstVariant, VariantTypes&&... Variants) { checkf((true && ... && Variants.IsValid()), TEXT("It is an error to call Visit() on an wrong TVariant. Please either check IsValid().")); return NAMESPACE_PRIVATE::TVariantVisitImpl::template Result::Do(Forward(Func), Forward(FirstVariant), Forward(Variants)...); } NAMESPACE_MODULE_END(Utility) NAMESPACE_MODULE_END(Redcraft) NAMESPACE_REDCRAFT_END