2014-09-04 38 views
1

我研究如何模板類的工作,我跟以下錯誤:一個std ::向量保存在自己的模板類

template <class T> 
class B 
{ 
    public: 
    std::vector<B<T> > queue; 
    B(); 
    ~B(); 
}; 

int main() 
{ 

    class B<int> tempQ(); 
    class B<int> temp2Q(); 
    class B<int> store(); 
    store.queue.push_back(tempQ); 
    store.queue.push_back(temp2Q); 
} 

它給了我一個編譯錯誤:

main.cpp:52:8: error: request for member 'queue' in 'store', which is of non-class type 'B<int>()' 
main.cpp:52:8: error: request for member 'queue' in 'store', which is of non-class type 'B<int>()' 

有人可以給我一些線索嗎?

而且模板B類裏面會使其

std::vector<B<T> > queue; 

std::vector<B> queue; 

回答

4

之間的差別有兩個不同的問題。首先,令人煩惱解析:

class B<int> store(); 

聲明瞭一個名爲store採取任何參數,並返回一個B<int>,而不是缺省構造變函數。只需編寫B<int> store;或在C++ 11中,B<int> store{};class也是多餘的,應該省略。

其次,

std::vector<B<T> > queue; 

實例與不完全型標準庫容器(一類的類型是不完整的,直到你打它的定義收盤}),這是不確定的行爲。根據實施情況,您可能能夠避開它,但您確實不應該這樣做。有非標準的容器(如those in Boost's containers library)保證支持不完整的類型 - 使用這些容器。

Also inside the template class B will it make a difference between

std::vector<B<T> > queue; 

and

std::vector<B> queue; 

沒有區別。在B的定義中,B之後的<T>在上下文需要類型(而不是模板)時是隱含的。

1

在你的代碼中,「class B tempQ();」並不意味着聲明變量 它只是聲明函數。

這裏是解決方案..

template <class T> 
class B 
{ 
    public: 
    std::vector<B<T>> queue; 
    B() {}; 
    ~B() {}; 
}; 

int main() 
{ 
    B<int> tempQ; 
    B<int> temp2Q; 
    B<int> store; 
    store.queue.push_back(tempQ); 
    store.queue.push_back(temp2Q); 
} 
相關問題