Suppose I have 2 classes, A and B, and I want A to execute a member function from B without explicitly knowing B’s type. I found a workaround using templates from the answer here, however I’m running into linker problems after I tried to implement it and try to compile it in UE4. This is what my code is so far:
ClassA.h:
#pragma once
#include "CoreMinimal.h"
class CPPTEST_API ClassA
{
public:
ClassA();
~ClassA();
template <typename UserClass>
void ExecuteArbitraryMethod(UserClass* ArbitraryClass, typename TMemFunPtrType<false, UserClass, void()>::Type InFuncs);
};
ClassA.cpp:
#include "ClassA.h"
ClassA::ClassA()
{
}
template <typename UserClass>
void ClassA::ExecuteArbitraryMethod(UserClass* ArbitraryClass, typename TMemFunPtrType<false, UserClass, void()>::Type InFuncs){
(ArbitraryClass->*InFuncs)();
}
ClassB.h:
#pragma once
#include "CoreMinimal.h"
class CPPTEST_API ClassB
{
public:
ClassB();
~ClassB();
void MethodToExecute();
};
ClassB.cpp:
#include "ClassA.h"
#include "ClassB.h"
ClassB::ClassB()
{
ClassA* ObjectA = new ClassA();
ObjectA->ExecuteArbitraryMethod(this, &ClassB::MethodToExecute); // Causes linking issues
}
ClassB::~ClassB()
{
}
void ClassB::MethodToExecute(){
UE_LOG(LogTemp, Warning, TEXT("ClassB method executed"));
}
After calling ExecuteArbitraryMethod from ClassB, I’m getting the following linking issue. If I remove that line, everything compiles fine.
CompilerResultsLog: Error: ClassB.cpp.obj : error LNK2019: unresolved external symbol "public: void __cdecl ClassA::ExecuteArbitraryMethod<class ClassB>(class ClassB *,void (__cdecl ClassB::*)(void))" (??$ExecuteArbitraryMethod@VClassB@@@ClassA@@QEAAXPEAVClassB@@P81@EAAXXZ@Z) referenced in function "public: __cdecl ClassB::ClassB(void)" (??0ClassB@@QEAA@XZ
)
CompilerResultsLog: Error: C:\UnrealProjects\CppTEST\Binaries\Win64\UE4Editor-CppTEST-6715.dll : fatal error LNK1120: 1 unresolved externals
Anyone have any ideas with what’s going wrong and might know how to fix it?