Ambiguous overload when using many typecasts operator overloads

好久不见. 提交于 2019-12-24 18:33:50

问题


I want to create a wrapperClass for strings. I also want the class to be able to return the address of the wrapperClass and the address of the stored (wrapped) string:

void FunctionString(string*);
void FunctionWrappedString(wrappedString*);

int main(){
   wrappedString wrappedStringObject;

   FunctionString(&wrappedStringObject);
   FunctionWrappedString(&wrappedStringObject);

   wrappedString anotherWrappedStringObject;

   if(wrappedStringObject == anotherWrappedStringObject){
    // code
   }
}

Here are the important parts of the class:

class wrappedString{
   typedef char* string;

   string storedString;

   operator string*(){
      // some code
      return &storedString;
   }

   operator wrapperString*(){
      // some code
      return this;
   }

  operator string(){
    // some code
    return storedString;
  }

}

However these fail when I use the comparison operator:

if(wrappedStringObject == anotherWrappedStringObject){
  // code
}

Saying that the candidates are: operator==(string,string) and operator==(string*,string*)


回答1:


Multiple implicit cast operators are causing this problem. If the goal is to have the wrapped string object behave like a string (which is actually a char*?!?), then only allow one implicit cast operator, while leaving the rest explicit to reduce the risk of misbehavior. This only works on C++11, but you should be using that by now anyway:

class wrappedString{
   typedef char* string;

   string storedString;

   explicit operator string*(){
      // some code
      return &storedString;
   }

   explicit operator wrapperString*(){
      // some code
      return this;
   }

   operator string(){
     // some code
     return storedString;
   }

}

With that definition, if(wrappedStringObject == anotherWrappedStringObject){ will only use the string overload, not the string* overload.



来源:https://stackoverflow.com/questions/37956250/ambiguous-overload-when-using-many-typecasts-operator-overloads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!