C++ Dynamic Return Type

Hello there,
I know this is not entirely possible in C++, but I was wondering:

How is possible to write a function that will change the return type the same way the blueprint “Create Widget” changes the return type based on the class in the input parameter?

Depends what you want to do and if you need it at compile time vs. runtime. If you want it at compile time, you can use templates.

template<typename T>
T MyFunc(T Input);

You can even have typetraits or other thing that define the output type based on the input type.

template<typename T>
typename typetraits<T>::ReturnType MyFunc(T Input);

You’ll need to define typetraits for each type T.

If you want to do this at runtime, there are many ways. You can use generic types like Variants. I think boost has some templated version of this. But there are generic types as well. So you can store whatever you want in them and then the caller has to check what the type is.

You can also use inheritance. So return the base class and then use RTTI to cast it to the derived type. RTTI is disabled in UE though.

Not sure if this answers your question. I’d need more info to give a more concise answer.

I’m creating an interface that is inherited and the function should always be available as it is(it’s more for utility)

Interface.h

UFUNCTION(BlueprintCallable, BlueprintNativeEvent, meta = (DeterminesOutputType = “Widget”), Category = “UI Management”) UUserWidget* CreateWidgetOnScreen(TSubclassOf Widget);

PlayerController.h

UFUNCTION(BlueprintCallable, BlueprintNativeEvent, meta = (DeterminesOutputType = “Widget”), Category = “UI Management”) UUserWidget* CreateWidgetOnScreen(TSubclassOf Widget);

PlayerController.cpp

UUserWidget* ABasePlayerController::CreateWidgetOnScreen_Implementation(TSubclassOf Widget)
{
UUserWidget* CreatedWidget = CreateWidget(GetWorld(), Widget);
CreatedWidget->AddToViewport();
return CreatedWidget;
}

Blueprint Compile

image

Compiler error

ErrorMsg=“COMPILER ERROR: failed building connection with 'User Widget Object Reference is not compatible with WBP Replace Equipment Slot Object Reference.' at Create Widget on Screen”