0

I've been attempting to create a component system for a game engine I have been writing. The component system should work similar to the Unity game engine component system e.g: gameObject.GetComponent<ComponentType>();

The problem in which I am facing is how can a template argument be used to find an object in a vector container. Below is a code sample of what I thought would be a working solution however I receive two compiler errors LNK2019 and LNK1120.

//Gets the first occurence of the specified Component type
//If the specified component type can not be found in the component container a null pointer is returned
template<class ComponentType> Component* GameObject::GetComponent()
{
    //Create temporary component
    ComponentType temporaryComponent = ComponentType();

    //For each component in the GameObjects component container
    for (unsigned int componentIndex = 0; componentIndex < m_componentContainer.size(); componentIndex++)
    {
        //If the component at component index in the component container is the same type as temporary component
        if (m_componentContainer[componentIndex]->GetType() == temporaryComponent.GetType())
        {
            //Return the component at component index in the component container
            return m_componentContainer.data()->get() + componentIndex;
        }
    }

    //The specified component type could not be found in the component container
    return nullptr;
}

I am aware that this function could be written like: Component* GetComponent(const unsigned char componentType);however since I am writing an engine that Unity developers should feel comfortable developing with I wish to copy Unity's class structure as accurately as possible.

Summary

Why am I receiving linker errors when attempting to compile the above code? I am not currently linking to any libraries/SDK's and have not changed any solutions settings for the project yet.

Zack
  • 1
  • 1
  • 3
    Most probably a duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – πάντα ῥεῖ Jun 20 '16 at 07:07
  • I thought that myself before posting but still received the same linker errors defining the function only in the header file – Zack Jun 20 '16 at 07:14
  • And what exactly does linker say? – PcAF Jun 20 '16 at 07:55
  • LNK1120: 1 unresolved externals – Zack Jun 20 '16 at 08:12
  • LNK2019: unresolved external symbol "public: class Component * __thiscall GameObject::GetComponent(void)" (??$GetComponent@VComponent@@@GameObject@@QAEPAVComponent@@XZ) – Zack Jun 20 '16 at 08:14

0 Answers0