2012-05-14 81 views
4

我試圖在模板中創建一種工廠類。我想做一些像純虛函數一樣的東西,但是當我使用函數來創建類型時,它需要是靜態的。模板類中的靜態函數

我想要發生的是當我聲明一個類,模板調用靜態函數。靜態函數實際上是在模板類中聲明的。

我得儘可能:

class Base 
{ 

}; 

template<typename T> 
class Type : public Base 
{ 
public: 
    static void Create() 
    { 
     mBase = CreateBase(); 
    } 

private: 
    static Base* CreateBase(); 

    static Base* mBase; 
}; 

class MyType : public Type<MyType> 
{ 
private:   
    static Base* CreateBase() 
    { 
     return new MyType; 
    } 
}; 

template<typename T> 
Base* Type<T>::mBase = NULL; 

void test() 
{ 
    MyType::Create(); 
} 

我得到一個鏈接時錯誤:

undefined reference to `Type<MyType>::CreateBase() 
+0

也參見[奇異遞歸模板模式](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)。 –

回答

1

找到它。

問題是我沒有調用派生類的函數。

這裏是修復:

static void Create() 
{ 
    mBase = T::CreateBase(); 
} 
2

CreateBase功能是在基本類型定義,所以才稱它爲:

template<typename T> 
class Type : public Base 
{ 
public: 
    static void Create() 
    { 
     mBase = Base::CreateBase(); 
    } 
//... 

無需在模板中聲明另一個CreateBase

+0

問題不在於我無法調用它,而是代碼沒有鏈接。 – Neil

+0

@Neil:在'Create'中,您正在調用未定義的Type <> :: CreateBase',因此鏈接器失敗。建議的解決方案是**不調用'Type <> :: CreateBase'(甚至不要聲明它!),並直接調用'MyType'中定義的'Base :: CreateBase',並且會正確鏈接。 –