即使在标头上实现,模板功能也会出现LNK2019错误

时间:2016-08-17 23:50:58

标签: c++ visual-studio

我有一个GameObject类,它有一个使用模板的组件系统(使用类型名)。但是没有建立,我也没有看到任何错误。

我已经搜索了很多,我能找到的唯一解决方案是将实现放在标题中,我做了。

感谢。

这是输出:

1>------ Build started: Project: SomeRandomProject, Configuration: Debug Win32 ------
1>  <some other files>
1>  Camera.cpp
1>  Sprite.cpp
1>  GameObject.cpp
1>Camera.obj : error LNK2019: unresolved external symbol "public: class Model * __thiscall GameObject::getComponent<class Model>(void)" (??$getComponent@VModel@@@GameObject@@QAEPAVModel@@XZ) referenced in function "public: void __thiscall Camera::render(class Level *)" (?render@Camera@@QAEXPAVLevel@@@Z)
1>Camera.obj : error LNK2019: unresolved external symbol "public: class Texture * __thiscall GameObject::getComponent<class Texture>(void)" (??$getComponent@VTexture@@@GameObject@@QAEPAVTexture@@XZ) referenced in function "public: void __thiscall Camera::render(class Level *)" (?render@Camera@@QAEXPAVLevel@@@Z)
1>Sprite.obj : error LNK2019: unresolved external symbol "public: void __thiscall GameObject::addComponent<class Model>(class Component *)" (??$addComponent@VModel@@@GameObject@@QAEXPAVComponent@@@Z) referenced in function "public: __thiscall Sprite::Sprite(class Texture *)" (??0Sprite@@QAE@PAVTexture@@@Z)
1>Sprite.obj : error LNK2019: unresolved external symbol "public: void __thiscall GameObject::addComponent<class Texture>(class Component *)" (??$addComponent@VTexture@@@GameObject@@QAEXPAVComponent@@@Z) referenced in function "public: __thiscall Sprite::Sprite(class Texture *)" (??0Sprite@@QAE@PAVTexture@@@Z)
1>C:\some\random\path.exe : fatal error LNK1120: 4 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

GameObject.h:

#pragma once

#include "Component.h"
#include <glm/glm.hpp>
#include <typeindex>
#include <string>
#include <vector>
#include <map>

class GameObject {
public:
    std::string name;
    glm::vec3 pos;
    glm::vec3 rot;

public:
    GameObject();
    ~GameObject();

    template<typename T>
    void addComponent(Component* component) {
        components[typeid(T)] = (void*) component;
        component->object = this;
        component->init();
    }

    template<typename T>
    T* getComponent() {
        return (T*) components[typeid(T)];
    }

    void update();

private:
    std::map<std::type_index, Component*> components;
};

0 个答案:

没有答案