簡體   English   中英

從模板化函數返回結構指針

[英]Return a struct pointer from templated function

當我這樣做時,我不斷收到鏈接器錯誤:

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

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

錯誤 LNK2019 未解析的外部符號“public: struct Position * __thiscall EntityManager::GetComponent(unsigned int,enum CType)” (??$GetComponent@UPosition@@@EntityManager@@QAEPAUPosition@@IW4CType@@@Z) 在函數 _main 中引用

我相信錯誤存在於“struct Position * GetComponent(...)”我不希望它返回一個“struct Position pointer”我希望它返回一個“Position pointer!” 我嘗試過各種模板前言,例如“class”和“struct”

我希望這成為可能,因為它比

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);

struct Position 繼承自 struct Component

正如我所說,如果我刪除模板並將“T”替換為“組件”然后 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>();

為什么? 我要問的是模板應該采用什么格式。

(是的,我測試了這個簡化的例子,請不要挑剔語法)

您不能像處理非泛型類那樣將使用泛型模板的類中的聲明和定義分開。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM