title: Using templates to get printf() to work with std::string
body: <p>I would like to generate a version of <code>printf</code> that automatically converts its <code>std::string</code> parameters to their <code>c_str()</code> values. (I find the <code>printf</code> syntax much cleaner and simpler than C++ streams). </p>
  
  <p>I want to use something SIMPLE. Short and simple is the only design goal. Boost has something like this but it is much too complex. I do NOT care about efficiency or avoiding copies at all. </p>
  
  <p>Below is a simple example that almost works with one parameter. There are two problems with the code:</p>
  
  <p>(1) How do I extend it to an arbitrary number (or say at least 3) parameters? I know I can use variadic templates, but I don't understand how to use them here. </p>
  
  <p>(2) How can I keep compiler warnings (under <code>clang</code> with <code>-Wall</code>) when there is a type mismatch between the format parameter <code>const char*</code> and the actual object to be printed? </p>
  
  <p>Edit: Part (2) has been nearly solved. I add a <code>__attribute__((format printf,1,2))</code> just before the <code>myprint()</code>. This does the typechecking but requires that <code>myprint</code> be variadic.</p>
  
  <p>Sample code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string&gt;
  using std::string;
  template &lt;typename T&gt;
  void myprint(const char* format, T arg){
    printf(format, arg);
  }
  
  template &lt;&gt;
  void myprint(const char* format, string arg){
    printf(format,(arg+" STRING ").c_str());
  }
  
  int main(){
    string x("foo");
    myprint ("The value of 1 is: %s\n", "simple"); //works
    myprint ("The value of 2 is: %s\n", x); // works
    myprint ("The value of 2 is: %d\n", x); // fails - no warning!
    printf ("The value of 2 is: %d\n", x.c_str()); // works - warning
    return 0;
  }
  </code></pre>