2011-04-20 64 views
2

我正在研究一段代碼,並且現在已經把我的頭撞到了諺語的牆上。我種的新模板的整體概念,因此希望任何和所有幫助我能在下面的問題:模板功能相關的編譯錯誤

我想建立一個對象生成器,需要一個allocator作爲參數這樣:

class Allocator { 
public: 
    allocate(unsigned int size, unsigned int alignment); 
    template <class T> 
    T* allocate_object() { return allocate(sizeof(T), alignof(T)); } 
}; 

template <class ALLOCATOR> 
class Builder { 
public: 
    Builder(ALLOCATOR& a) : a(a) {} 
    void build_something() { 
     int* i = a.allocate_object<int>(); 
    } 
private: 
    ALLOCATOR& a; 
}; 

當我嘗試調用「build_something」功能與我的分配器我碰到下面的編譯錯誤:

分配器對自己的作品爲「錯誤‘INT’之前預期基本表達式」但不能像示例中那樣用作模板參數。那麼,有什麼我可以做的解決這個問題,而不必在分配器中放棄模板函數?

最好我會喜歡用多態性來發送指向構建器的分配器(基類)對象 指針,但顯然你不能有虛擬模板函數。 :)

謝謝你的時間! :) -Maigo

回答

3
int* i = a.template allocate_object<int>(); 

C++ template gotchas

+0

更良好的閱讀材料:?什麼是 - >模板,.template和::有關模板語法(http://www.comeaucomputing.com/ techtalk /模板/#templateprefix) – ildjarn 2011-04-21 09:58:39