I wrote very clear way to do this.
Snippet from here: Interface implementation check for Unreal Engine 4 (UE4) ($1832992) · Snippets · District Zero / Unreal Engine 4 Snippets · GitLab
Code:
#pragma once
#include "Interface.h"
/**
* Fast and full checking of interface implementation including nullptr check, C++ cast check and blueprint check
* @param TIInterfaceType is interface IClass (not UClass)
* @param object is pointer to check
* @return true if object implements TIInterfaceType, false if nullptr or doesn't implement
*/
template<typename TIInterfaceType>
FORCEINLINE bool IsInterfaceImplementedBy(const UObject* const object)
{
return
// Nullptr is invalid
object &&
// C++-style cast much faster
(Cast<TIInterfaceType>(object) ||
// But blueprint implementation pass only this check
object->GetClass()->ImplementsInterface(TIInterfaceType::UClassType::StaticClass()));
}
You need to include this header into every interface declaration and use it in C++:
void ATestCodeGameModeBase::CallDoSomething(UObject* object)
{
// Clear check of what we mean
if (IsInterfaceImplementedBy<ITestInterface>(object))
{
ITestInterface::Execute_DoSomething(object);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Object does not implement interface"));
}
}
// vs
void ATestCodeGameModeBase::CallDoSomething(UObject* object)
{
// Doesn't understandable
if (object && object->GetClass()->ImplementsInterface(UTestInterface::StaticClass()))
{
ITestInterface::Execute_DoSomething(object);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Object does not implement interface"));
}
}