title: C++ Implicit Conversion Operators Precedence
body: <p>EDIT: Following Mike Seymour's comment, I replaced <code>operator std::string () const;</code> with <code>operator char * () const;</code> and changed the implementation accordingly. This allows implicit casting, but, for some reason, the unsigned long int operator has precedence over the char * operator, which just does not feel right... Also, I don't want to expose nasty C stuff like char * outside the class, when I have std::string. I have a hunch that my CustomizedInt class needs to inherit from some stuff in order to support the feature that I desire. Could anybody please elaborate Mike's comment regarding <code>std::basic_string</code>? I'm not sure I understood it properly.</p>
  
  <hr>
  
  <p>I have this piece of code:</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;sstream&gt;
  #include &lt;iostream&gt;
  
  class CustomizedInt
  {
  private:
      int data;
  public:
      CustomizedInt() : data(123)
      {
      }
      operator unsigned long int () const;
      operator std::string () const;
  };
  
  CustomizedInt::operator unsigned long int () const
  {
      std::cout &lt;&lt; "Called operator unsigned long int; ";
      unsigned long int output;
      output = (unsigned long int)data;
      return output;
  }
  
  CustomizedInt::operator std::string () const
  {
      std::cout &lt;&lt; "Called operator std::string; ";
      std::stringstream ss;
      ss &lt;&lt; this-&gt;data;
      return ss.str();
  }
  
  int main()
  {
      CustomizedInt x;
      std::cout &lt;&lt; x &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  
  <p>Which prints "Called operator unsigned long int; 123". My questions are these:</p>
  
  <ol>
  <li>After I remove the operator unsigned long int, why do I need to cast x to std::string explicitly? Why does it not call the implicit cast operator (std::string) directly?</li>
  <li>Is there any documentation that explains which implicit casts are allowed and which is their order of precedence? It seems that if I add an operator unsigned int to this class together with the operator unsigned long int, I receive a compiler error about ambiguity for the &lt;&lt; operator...</li>
  <li>Also, I know that defining such an operator may be poor practice, but I am not sure I fully understand the associated caveats. Could somebody please outline them? Would it be better practice to just define public methods ToUnsignedLongInt and ToString?</li>
  </ol>