2013-06-27 54 views
0

有問題I'm而編寫資源類:與模板成員函數的C++繼承類

class BaseResource { 
protected: 
    unsigned int size; 

public: 
    virtual ~BaseResource() {} 
    template<class T> const T& GetValue() const; 
    template<class T, class U> void GetValue(const U& rhs); 

    unsigned int GetSize() { 
     return this->size; 
    } 
    void SetSize(unsigned int size) { 
     this->size = size; 
    } 
}; 

template<class T> 
class Resource : public BaseResource { 
    T value; 

public: 
    virtual ~Resource() {}  
    Resource(unsigned int size, const T& rhs) { this->size = size; this->value = rhs; } 

    const T& GetValue() const {return value;} 
    void SetValue(const T& rhs) {value=rhs;} 
}; 

我覺得上面的類正確定義,所以我 不明白爲什麼下面的代碼生成一個鏈接錯誤:

Test.obj:錯誤LNK2001:無法解析的外部符號 「」 市民:char * const的& __thiscall BaseResource ::的GetValue(無效)常量 「(?? $ @的GetValue PAD @ BaseResource @@ QBEABQADXZ)」。

char* c = new char[3]; 
c[0] = '1'; 
c[1] = '2'; 
c[2] = '3'; 
BaseResource* resource = new Resource<char*>(3, c); 
char* loadedResource = resource->GetValue<char*>(); 

在我看來,這應該創建一個資源的實例持有一個char *並可以返回它。

有人可以告訴我,我在哪裏做了這個錯誤嗎?

回答

2

這些函數的實現應該與類相同的頭文件中。在這種情況下,您已經實例化了模板函數,並且具體的實例化函數沒有被定義。每次使用模板時,都需要在使用該功能的翻譯單元中包含該功能的定義。

編輯


這是基本的理念。您需要定義植入,以便在類實例化時類已完全定義。

public: 
    virtual ~BaseResource() {} 
    template<class T> const T& GetValue() const 
    { 
     return someT; 
    } 
    template<class T, class U> void GetValue(const U& rhs) 
    { 
     return someT; 
    } 

    unsigned int GetSize() { 
     return this->size; 
    } 
    void SetSize(unsigned int size) { 
     this->size = size; 
    } 
}; 
+0

嗯好吧,這似乎合乎邏輯。 那麼你能明確告訴我如何解決所示情況的問題嗎? – Xenogenesis

2

下面的方法未實現:

template<class T> const T& GetValue() const; 
template<class T, class U> void GetValue(const U& rhs); 

我希望你是不是在讓他們的虛擬因爲西港島線不工作規劃。 模板方法不能做成虛擬的。 因爲它們沒有被實現,所以明確解釋了鏈接問題。