繁体   English   中英

模板中的C ++重载operator =

[英]C++ overloading operator= in template

大家好,我在使用C ++模板运算符时遇到了麻烦

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

图形运算符=:

      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

只是一个猜测,您是否偶然在复制构造函数和赋值中缺少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的特殊“持有人”类来实现移动语义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM