2012-04-28 157 views
2

模板類我想創建一個模板類的靜態函數靜態函數

template <typename T> 
class Memory 
{ 
public: 
    template < typename T> 
    static <T>* alloc(int dim) 
    { 
    T *tmp = new T [ dim ]; 
    return tmp; 
    }; 
} 

,但我總是會得到

int *a = Memory::alloc<int>(5) 

我不知道該怎麼機會..

»template<class T> class Memory« used without template parameters 
expected primary-expression before »int« 
Fehler: expected »,« or »;« before »int« 
+0

我不編譯,最後一個codebox是問題:) – Roby 2012-04-28 12:55:10

+0

@Tudor:鑑於OP發佈了編譯器錯誤消息,大概不是! – 2012-04-28 12:55:11

回答

6

當您可能只想爲其中的一個模板時,您正在模板類和函數。

這是你的意思嗎?

template <typename T> 
class Memory 
{ 
public: 
    static T* alloc(int dim) 
    { 
    T *tmp = new T [ dim ]; 
    return tmp; 
    }; 
} 

int *a = Memory<int>::alloc(5); 

這裏有一個正確的版本既:

template <typename T> 
class Memory 
{ 
public: 
    template <typename U> 
    static U* alloc(int dim) 
    { 
    U *tmp = new U [ dim ]; 
    return tmp; 
    }; 
} 

int *a = Memory<float>::alloc<int>(5); 

您可以刪除外模板,如果你只是想作爲模板的功能。

+0

ahh oki,那麼是否有可能通過模板靜態T * alloc ...來實現功能? – Roby 2012-04-28 12:56:33

+0

@羅比我不完全明白你的意思,但我已經用另一個例子更新了這篇文章。 – Pubby 2012-04-28 12:58:35

+0

真的很感謝! :) – Roby 2012-04-28 13:02:27