2015-10-06 115 views
-1

我不斷收到鏈接錯誤,返回一個結構指針,當我這樣做:從模板功能

//function declaration 
template<typename T> 
T * EntityManager::GetComponent(EID _entity, CType _type) 

//Main.cpp 
Position * pos = GetComponent<Position>(eid, POSITION); 

錯誤LNK2019解析的外部符號「公用:結構位置* __thiscall的EntityManager :: GetComponent(unsigned int類型,枚舉CTYPE) 「 (?? $ @ GetComponent @@@ UPosition EntityManager的@@ QAEPAUPosition @@ IW4CType @@@ Z) 函數引用_main

我認爲錯誤在於」 ST Ruct位置* GetComponent(...)「 我不希望它返回一個」結構位置指針「 我希望它返回一個」位置指針!「 我已經試過各種模板序跋,如「類」和「結構」

我想這是可能的,因爲它比

Position * pos = static_cast<Position *>(GetComponent(eid, POSITION)); 

簡潔得多(這不工作)

感謝您的幫助!

編輯: 下面是完整的源代碼,以證明它不是功能,而是一些與模板做...

//EntityManager.h 
template<typename T> 
T * GetComponent(EID _entity, CType _type); 

//EntityManager.cpp 
template<typename T> 
T * EntityManager::GetComponent(EID _entity, CType _type) 
{ 
    T * component = nullptr; 
    int index = GetComponentIndex(_entity, _type); 

    if (index >= 0) 
     component = m_entities.find(_entity)->second[index]; 

    return component; 
} 

//Main.cpp 
EntityManager EM; 
Position * pos = EM.GetComponent<Position>(eid, POSITION); 

結構的位置,從結構組件

正如我所說的繼承,如果我刪除模板並將「T」替換爲「Component」,則static_cast返回值,該功能完美地工作。我想避免使用靜態澆鑄

編輯編輯......

這編譯:

//EntityManager.h 
class EntityManager 
{ 
public: 
    Component * GetComponent(); 
}; 

//EntityManager.cpp 
Component * EntityManager::GetComponent() 
{ 
return new Position; 
} 

//Main.cpp 
EntityManager EM; 
Position * pos = static_cast<Position *>(EM.GetComponent()); 

這不:

//EntityManager.h 
class EntityManager 
{ 
public: 
    template<typename T> 
    T * GetComponent(); 
}; 

//EntityManager.cpp 
template<typename T> 
T * EntityManager::GetComponent() 
{ 
return new T; 
} 

//Main.cpp 
EntityManager EM; 
Position * pos = EM.GetComponent<Position>(); 

爲什麼? 所有我問的是應該是什麼格式的模板。

(是的,我測試了這個簡化的例子,請不要雞蛋裏挑骨頭的語法)

+2

在我看來,這不是由於返回類型,而是由於它沒有在正確的位置找到模板的主體。你在哪裏定義身體?它需要在某個地方可以看到它在哪裏使用,通常在頭文件中 – jcoder

+1

什麼是EntityManager?它是一個類還是一個命名空間?爲什麼它不會在你的「main」調用中出現? –

+2

您是否定義了該功能?在頭文件中? – emlai

回答

1

你不能單獨的聲明和定義在其中的類使用泛型模板,就像使用非泛型類一樣。

嘗試將您所有的EntityManager.cpp移動到EntityManager.h

+0

非常感謝。 :d – BenSeawalker