Cory Klein
Cory Klein

Reputation: 55690

Why can the compiler find one of these operator overloads but not the other?

I am trying to serialize a custom class I have made, given a pointer to an instance of the class. This code fails to compile because it can't resolve the operator<<(out, myObj).

QDataStream& operator<<(QDataStream &out, MyObj const *&m);
QDataStream& operator>>(QDataStream &in, MyObj *&m);

void MainWindow::serialize(QDataStream &out)
{
  MyObj *myObj = new MyObj();
  operator<<(out, myObj);
}

void MainWindow::deserialize(QDataStream &in)
{
  MyObj *myObj = new myObj();
  operator>>(in, myObj);
}

QDataStream &operator<<(QDataStream &out, MyObj const *&) { return out; }

QDataStream &operator>>(QDataStream &in, MyObj *&) { return in; }

The compile error is as follows:

MainWindow.cpp:79:33: error: call of overloaded 'operator<<(QDataStream&, MyObj*&)' is ambiguous
MainWindow.cpp:79:33: note: candidates are:
../Qt5.0.1/5.0.1/gcc_64/include/QtCore/qchar.h:395:28: note: QDataStream& operator<<(QDataStream&, QChar) <near match>
../Qt5.0.1/5.0.1/gcc_64/include/QtCore/qchar.h:395:28: note:   no known conversion for argument 2 from 'MyObj*' to 'QChar'
...

Interestingly, the compiler only fails to find the first operator overload. I am able to fix this by using object references rather than references to object pointers, but I am curious why this will not compile.

Why would the compiler be unable to find the implementation of the first operator?

Upvotes: 2

Views: 258

Answers (1)

Drew Dormann
Drew Dormann

Reputation: 63775

In your call to operator<<, you are attempting to cast a MyObj* to a MyObj const *&.

At first glance, this looks valid. You are adding const-ness, after all. But C++ does not allow it.

Consider this possible implementation of your function to see why.

QDataStream &operator<<( QDataStream &out, MyObj const *& refptr )
{
   static const MyObj const_thing;
   refptr = &const_thing;
   return out;
}

This code would modify the supplied (non-const) pointer MyObj *myObj to now point to an object that was declared as const.

If you want that particular function signature You can fix this by providing a const-correct pointer to reference.

void serialize(QDataStream &out)
{
  MyObj *myObj = new MyObj();
  const MyObj *myConstObj = myObj; // THIS is the pointer that will be referenced
  operator<<(out, myConstObj);
}

Otherwise, consider just removing the reference.

QDataStream& operator<<(QDataStream &out, MyObj const *m);

Upvotes: 1

Related Questions