2009-11-21 54 views
0

大家好我在與C++模板操作麻煩=C++運算符重載=模板

我想要做的事: 我使用CUDA上的圖形算法的項目工作,我們有幾個不同的基準圖形格式。另外,我不完全確定我們最終將使用哪種類型的圖表的各個元素。
我的目標是擁有一個模板圖類和許多其他類,每個類都將知道如何加載特定格式。除了graphCreator類從generate函數返回一個圖類型的點之外,一切似乎都可以正常工作。 這裏是我的代碼:

圖opertator =:

 MatrixGraph<T>& operator=(MatrixGraph<T>& rhs) 
     { 
     width = rhs.width; 
     height = rhs.height; 
     pGraph = rhs.pGraph; 
     pitch = rhs.pitch; 
     sizeOfGraph = rhs.sizeOfGraph;  
     rhs.Reset(); 
     } 

的rhs.reset()調用消除了分配的內存全部引用,以便它們不會被RHS被釋放。只允許一個圖形引用分配的圖形內存。

圖形拷貝構造函數:

MatrixGraph(MatrixGraph<T>& graph) 
    { 
     (*this) = graph; 
    } 

圖造物主負載功能:

MatrixGraph<T> LoadDIMACSGraphFile(std::istream& dimacsFile) 
{ 
char inputType; 
std::string input; 

GetNumberOfNodesAndEdges(dimacsFile, nodes, edges); 

MatrixGraph<T> myNewMatrixGraph(nodes); 

while(dimacsFile >> inputType) 
{ 
    switch(inputType) 
    { 
    case 'e': 
     int w,v; 
     dimacsFile >> w >> v; 
     myNewMatrixGraph[w - 1][v - 1] = 1; 
     myNewMatrixGraph[v - 1][w - 1] = 1; 
     break; 

    default: 
     std::getline(dimacsFile, input); 
     break; 
    } 
} 

    return myNewMatrixGraph; 
} 

最後在main.cpp中,其中我試圖單元測試這一點,我使用它:

DIMACSGraphCreator<short> creator; 
myGraph = creator.LoadDIMACSGraphFile(instream); 

當我嘗試編譯時,我得到這個錯誤:

main.cpp: In function 'int main(int, char**)': 
main.cpp:31: error: no match for 'operator=' in 'myGraph = DIMACSGraphCreator<T>::LoadDIMACSGraphFile(std::istream&) [with T = short int](((std::istream&)(& instream.std::basic_ifstream<char, std::char_traits<char> >::<anonymous>)))' 
MatrixGraph.h:103: note: candidates are: MatrixGraph<T>& MatrixGraph<T>::operator=(MatrixGraph<T>&) [with T = short int] 
make: *** [matrixTest] Error 1 
+0

您不顯示'myGraph'的聲明。我們需要這個。 – 2009-11-21 20:22:39

+0

此外,你似乎忽略了你的聲明中的「模板」部分...你可以添加它嗎? – 2009-11-21 20:23:30

回答

1

問題是你正在返回值(正確),但試圖將該臨時對象綁定到非const引用(對於op =參數)。你不能這樣做。

解決的辦法是改變周圍的事物,這可能會導致非慣用的代碼;使用類似auto_ptr_ref的構造,它以相當糟糕但封裝的方式解決這個問題;或者使用專爲這種情況設計的r值參考。但是,r值引用僅作爲C++ 0x的一部分提供,您的編譯器可能不支持它們。

請務必在您的op =中返回*this。沒有警告打開你的編譯器可能會默默地(並違背標準)接受那個函數而沒有返回語句。 (我不知道爲什麼。)第一個解決方案的

例子:

// move return value into output-parameter: 
void LoadDIMACSGraphFile(std::istream& dimacsFile, MatrixGraph<T>& dest); 

// ... 

DIMACSGraphCreator<short> creator; 
creator.LoadDIMACSGraphFile(instream, myGraph); 

std::auto_ptr是在該stdlib的,並使用一個特殊的「持有」級命名auto_ptr_ref來實現移動語義。

3

只是一個猜測,你是偶然的錯過你的複製構造函數和賦值const限定符?