C ++重载operator = in template

时间:2009-11-21 20:15:30

标签: c++ templates operator-overloading

大家好我没遇到C ++模板operator =

我正在尝试做什么: 我正在使用cuda进行图算法项目,我们有几种不同的格式用于基准测试图。另外,我不完全确定我们最终会使用什么类型的图表的各个元素 我的目标是拥有一个模板化的图表类和许多其他类,每个类都知道如何加载特定的格式。除了graphCreator类从generate函数返回图形类型之外,所有内容似乎都可以正常工作。 这是我的代码:

Graph 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;
   }

Graph Creator加载功能:

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

2 个答案:

答案 0 :(得分:3)

只是一个猜测,您是否偶然在复制构造函数和赋值中缺少const限定符?

答案 1 :(得分:1)

问题是你是按值(正确)返回,但是试图将该临时对象绑定到非const引用(对于op =参数)。你不能这样做。

解决方案是改变现状,这可能导致非惯用代码;使用类似auto_ptr_ref的构造,它以一种相当糟糕但封装的方式绕过它;或者使用r值引用,它们是针对这种情况而设计的。但是,r值引用仅作为C ++ 0x的一部分提供,并且您的编译器可能还不支持它们。

确保在您的op =中返回*this。如果没有启用警告,您的编译器可能会默默地(并且违反标准)接受该函数而不使用return语句。 (我不知道为什么。)

第一个解决方案的示例:

// 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的特殊“holder”类来实现移动语义。