title: Templated operator instantiation and type conversion
body: <p>This if for the C++ gurus out there.</p>
  
  <p>Consider the following code:</p>
  
  <pre><code>class X { };
  
  template &lt;class T&gt;
  class Mistake {
  public:
    T x;
  
    Mistake(const T&amp; k) : x(k) { }
    Mistake(const X&amp;) : x(1) { }
  
    void print() { cout &lt;&lt; x &lt;&lt; endl; }
  };
  
  template &lt;class T&gt;
  Mistake&lt;T&gt; operator+(const Mistake&lt;T&gt;&amp; a, const Mistake&lt;T&gt;&amp; b)
  {
    return Mistake&lt;T&gt;(a.x + b.x);
  }
  </code></pre>
  
  <p>I have a class "Mistake" for which I want to have the addition operation. When I try:</p>
  
  <pre><code>X a, b;
  Mistake&lt;int&gt; foo = a + b;
  </code></pre>
  
  <p>I get a compilation error; the compiler cannot seem to realize that the template operator+ has to be instantiated.</p>
  
  <p>If, on the other hand, I add the following piece of code before:</p>
  
  <pre><code>Mistake&lt;int&gt; operator+(const Mistake&lt;int&gt;&amp; a, const Mistake&lt;int&gt;&amp; b)
  {
    return Mistake&lt;int&gt;(a.x + b.x);
  }
  </code></pre>
  
  <p>then all is well. Anyone has any clue why? I suspect the compiler cannot figure out what to instantiate because of the type conversion needed from class X to class Mistake, but I don't know how to fix this issue short of not using templates at all.</p>
  
  <p>By the way, defining the operator inside the class as a friend also doesn't work.</p>
  
  <p>Thanks!</p>