title: How to allow derived classes in a C++ template argument
body: <p>I want to write a function that accepts a collection of type <code>T</code>, say <code>std::vector&lt;T&gt;</code>, but that does two different things depending on <code>T</code>.  For example, if <code>T</code> is <code>==</code> comparable, then use <code>a == b</code>, else if <code>T</code> has a <code>.value</code> element, use that (<code>a.value == b.value</code>).</p>
  
  <p>My first attempt was to use an overloaded function, but that fails if I pass in a derived class (subclass) of <code>T</code>.</p>
  
  <p>Suppose, for example, I want to create an <code>Exists</code> method.  (I know this can be implemented using <code>std::find_if</code>; it is an example only.)  The following fails to compile:</p>
  
  <pre><code>using namespace std;
  
  struct Base {
      Base(string s) : value(std::move(s)) {}
      string value;
  };
  
  struct Derived : public Base {
      Derived(string s) : Base(std::move(s)) {}
  };
  
  bool Exists(const vector&lt;string&gt;&amp; collection, const string&amp; item) {
      for (const auto&amp; x : collection)
          if (x == item)
              return true;
      return false;
  }
  
  bool Exists(const vector&lt;Base&gt;&amp; collection, const Base&amp; item) {
      for (const auto&amp; x : collection)
          if (x.value == item.value)
              return true;
      return false;
  }
  </code></pre>
  
  <p>This works fine for exact matches, such as:</p>
  
  <pre><code>Exists(vector&lt;string&gt;{"a", "b", "c"}, "b");
  Exists(vector&lt;Base&gt;{{"a"}, {"b"}, {"c"}}, Base{"b"});
  </code></pre>
  
  <p>But it fails for derived classes:</p>
  
  <pre><code>Exists(vector&lt;Derived&gt;{{"a"}, {"b"}, {"c"}}, Derived{"b"})
  </code></pre>
  
  <p>The error is:</p>
  
  <pre><code>foo.cc:35:13: error: no matching function for call to 'Exists'
  foo.cc:23:6: note: candidate function not viable: no known conversion from 'vector&lt;Derived&gt;' to 'const vector&lt;Base&gt;' for
      1st argument
  </code></pre>
  
  <p>How can I solve this?  I am interested in multiple answers, since each solution probably has pros and cons.</p>