2017-05-07 55 views
1

我已瀏覽了本網站和其他網站上的數十篇文章,並且找不到解決此特定問題的單個文章。考慮這個SparseGraph類我的工作:模板和在.cpp文件中使用聲明

Sparse_Graph.h

template <typename NodeType, typename EdgeType> 
class SparseGraph 
{ 
    //... 
public: 
    SparseGraph(); 
    //... 
}; 

爲了縮短在我的.cpp文件中的代碼,我希望做類似的東西:

Sparse_Graph的.cpp

#include "Sparse_Graph.h" 

template<typename NodeType, typename EdgeType> 
using SGraph = SparseGraph<NodeType, EdgeType>; 

SGraph::SparseGraph() {} 

這對我來說特別重要,因爲後來在這個文件我寫了作爲一個迭代函數聲明:

template <typename NodeType, typename EdgeType> 
typename SparseGraph<NodeType, EdgeType>::EdgeIterator& 
SparseGraph<NodeType, EdgeType>::EdgeIterator::operator++() 

(耶)

特別是,在嘗試這個時候我得到的錯誤是:

無效使用模板名 'SGraph' 沒有一個參數列表

所以我的問題是:我怎麼能得到這樣的事情,所以我不必在我的.cpp文件中編寫3行函數頭?


enter image description here

+2

這是因爲'NodeType'和'EdgeType'是通用的,而不是實際的類型。你需要說'使用SGraph = SparseGraph ...(IIRC) – Charles

+0

template using SGraph = SparseGraph :: Node,SparseGraph <節點類型,EdgeType> ::邊緣>; 不起作用。 (我在類聲明中使用了Edge和Node的聲明)。我認爲這些也不符合實際類型。 – AldenB

+1

您不能將實現放在.cpp文件中,因爲編譯器必須能夠在實例化模板的具體類型的地方看到它。 [看到這個問題](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file)。 – zett42

回答

0

SGraph::SparseGraph() {}SGraph是一個別名模板,所以你不能沒有參數列表中使用它。 您需要使用這樣的:

template <typename NodeType, typename EdgeType> 
SGraph<NodeType,EdgeType>::SparseGraph() {} 
+0

這對我的情況沒有任何幫助。現在我的函數頭看起來像\t模板 typename SGraph :: EdgeIterator&SGraph :: EdgeIterator :: operator - () – AldenB