title: How does a templated class resolve an overloaded non-member function called on one of its types?
body: <p>In the following example, I've created a mock Container class for an arbitrary type. Calling compare() on the Container calls compare() for the Value object stored inside. How is the compare() function overloaded for Value resolved in <code>Container&lt;Value&gt;</code> when it is declared afterwards and is not a member function of Value?</p>
  
  <p>Code:</p>
  
  <pre><code>template&lt;typename T&gt;
  class Container
  {
  public:
      Container(T value) : element(value) {}
      T element;
  };
  
  template&lt;typename T&gt;
  int compare(Container&lt;T&gt; const&amp; first, Container&lt;T&gt; const&amp; second)
  {
      return compare(first.element, second.element);
  }
  
  class Value
  {
  public:
      Value(int value) : value(value) {}
      int value;
  };
  
  int compare(Value const&amp; first, Value const&amp; second)
  {
      if (first.value &lt; second.value)
          return -1;
      else if (first.value &gt; second.value)
          return 1;
      return 0;
  }
  
  int main()
  {
      auto l1 = Container&lt;Value&gt;(1);
      auto l2 = Container&lt;Value&gt;(1);
      auto l3 = Container&lt;Value&gt;(2);
  
      cout &lt;&lt; compare(l1, l2) &lt;&lt; endl;
      cout &lt;&lt; compare(l1, l3) &lt;&lt; endl;
  }
  </code></pre>
  
  <p>Output (as expected):</p>
  
  <pre><code>0
  -1
  </code></pre>