Announcement

Collapse
No announcement yet.

Template UClass or an other way ?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Template UClass or an other way ?

    Hello dev, i would like to make something like that :

    Code:
    template <class T>
    UCLASS()
    class PROJECT_API AMyActor : public AActor
    {
        GENERATED_BODY()
    
    public:
        AMyActor();
    
        UPROPERTY(EditDefaultsOnly)
        T* MyComponent = nullptr;
    }
    
    AMyActor<T>::AMyActor()
    {
        MyComponent = CreateDefaultSubobject<T>("MyComp");
    }
    
    UCLASS()
    class PROJECT_API AMyChildActor : public AMyActor<USceneComponent>
    {
        GENERATED_BODY()
    }
    obviously, he doesn't compile. But, my questions :

    Can we have template UClass ? If yes, how please ?
    Did you see a design pattern for make something like that or a tips ?

    Thank's for the read,
    Have a nice day !

    #2
    No, you can't use templates with reflection or UObjects.

    There are a handful of special templated containers in UE4 that support reflection such as TArray, TMap and TSet etc, but they all have special handling.

    Comment


      #3
      Ok thank's

      Comment


        #4
        I have something, but for this moment we can't edit component in editor, but it's work.

        Code:
        class UMyGenericClass
        {
        public:
            UMyGenericClass()
            {}
        
            UMyGenericClass(AActor* _actor)
            {}
        };
        
        template<class T>
        class UMyTemplateClass : public UMyGenericClass
        {
        public:
            UMyTemplateClass(AActor* _actor)
                : UMyGenericClass() 
            {
                if (_actor)
                {
                    MyComponent = _actor->CreateDefaultSubobject<T>("MyComp");
                }
            }
        
        public:
            T* MyComponent = nullptr;
        };
        
        template<class T>
        struct STag { using type=T; };
        
        UCLASS()
        class USETEMPLATE_API AMother : public AActor
        {
            GENERATED_BODY()
        
        public:    
            // Sets default values for this actor's properties
            AMother();
            template<class T>
            AMother(STag<T> _tag);
        
        public:
            UMyGenericClass GenericClass;
        };
        
        template<class T>
        AMother::AMother(STag<T> _tag)
        {
            GenericClass = UMyTemplateClass<T>(this);
            PrimaryActorTick.bCanEverTick = true;
        }
        and in my .cpp

        Code:
        // Sets default values
        AMother::AMother()
            : AMother(STag<USceneComponent>{})
        {
        }
        if you have any question, you can mp me

        Comment

        Working...
        X