Writing static template method on source file

Hi, people.
I was wondering if you know any way of avoid using Header files to define static template methods (bc linker gets confused with symbols when you put the definition on Source file, like shows the following capture)


Here I’m showing all it’s OK when simply move the definition to Header:

I know it’s C++ stuff, not Unreal fault, but maybe you know any arrangement; I find it quite messy to have everything in the header.

Some context

Giving more context: that’s a Blueprint Function Library class for ActorComponents generics.

Thanks you all :slight_smile:

You have two problems here:

First, you cannot expose templates to blueprint. At least not easily. It is possible to write generic functions for specific containers that are supported by blueprint.

Second, generally template definitions (the body of the function) have to be visible to any place that uses it so it has to go into the header (unless it’s a template only used within one cpp).

Now, in your particular case you could declare a function like this:

UFUNCTION(BlueprintCallable, meta = (DeterminesOutputType = "Type"))
UActorComponent* GetComponent(TSubclassOf<UActorComponent> Type, AActor *Owner);

The ‘Type’ parameter will create a drop down that allows you to select a component type and the metadata markup will autocast the return value to that type.

BUT: You shouldn’t need to write your own library function for this. Actor already has a template function that you can call like this: Actor->GetComponentByClass< CompType >( ) that does exactly what you want (sans logging).
Also, there is already a blueprint node to do this that works the way you want where you pick a type and the return is autocast for you.

1 Like

Thank u, @MagForceSeven.
I am not that much interested on expose this method to BP, I just did it for possible future testing on BP; anyway, I noted your valuable information for the next time.
I already knew templates must be on header, but I was looking for some kinda trick to bypass this necessity and be able to define it on source. I guess I have to get over it my order obsession in this case :joy: .

I thank you too for the tip about direct get method with already casted component, but I tried it and I think you maybe meant to FindComponentByClass<CompType>().

Thank u again for your time.

It’s possible it depends on the version that you have. I’m on 5.2 and Actor definitely has a GetComponentByClass template function.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.