2009-11-21 106 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限定符?