title: Undefined reference to function template when used with string (GCC)
body: <p>I need to write a templated function <code>replace_all</code> in C++ which will take a string, wstring, glibmm::ustring etc. and replace all occurrences of <code>search</code> in <code>subject</code> with <code>replace</code>.</p>
  
  <p>replace_all.cc</p>
  
  <pre><code>template &lt; class T &gt;
  T replace_all(
          T const &amp;search,
          T const &amp;replace,
          T const &amp;subject
  ) {
          T result;
  
          typename T::size_type done = 0;
          typename T::size_type pos;
          while ((pos = subject.find(search, done)) != T::npos) {
                  result.append (subject, done, pos - done);
                  result.append (replace);
                  done = pos + search.size ();
          }
          result.append(subject, done, subject.max_size());
          return result;
  }
  </code></pre>
  
  <p>test.cc</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  template &lt; class T &gt;
  T replace_all(
          T const &amp;search,
          T const &amp;replace,
          T const &amp;subject
  );
  
  // #include "replace_all.cc"
  
  using namespace std;
  
  int main()
  {
          string const a = "foo bar fee boor foo barfoo b";
          cout &lt;&lt; replace_all&lt;string&gt;("foo", "damn", a) &lt;&lt; endl;
          return 0;
  }
  </code></pre>
  
  <p>When I try to compile this using gcc 4.1.2  </p>
  
  <pre><code>g++ -W -Wall -c replace_all.cc  
  g++ -W -Wall -c test.cc  
  g++ test.o replace_all.o  
  </code></pre>
  
  <p>I get:</p>
  
  <pre><code>test.o: In function `main':
  test.cc:(.text+0x13b): undefined reference to `
     std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;
     replace_all&lt; std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;(
         std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;,
         std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;,
         std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;
     )
  '
  collect2: ld returned 1 exit status
  </code></pre>
  
  <p>But when I uncomment <code>#include "replace_all.cc"</code> in test.cc and compile this way:</p>
  
  <pre><code>g++ -W -Wall test.cc
  </code></pre>
  
  <p>The program links and produces expected output:</p>
  
  <pre><code>damn bar fee boor damn bardamn b
  </code></pre>
  
  <p>Why linking fails and what can I do to make it work?</p>