I would like to generate a version of printf
that automatically converts its std::string
parameters to their c_str()
values. (I find the printf
syntax much cleaner and simpler than C++ streams).
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.
Below is a simple example that almost works with one parameter. There are two problems with the code:
(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.
(2) How can I keep compiler warnings (under clang
with -Wall
) when there is a type mismatch between the format parameter const char*
and the actual object to be printed?
Edit: Part (2) has been nearly solved. I add a __attribute__((format printf,1,2))
just before the myprint()
. This does the typechecking but requires that myprint
be variadic.
Sample code:
#include <stdio.h>
#include <string>
using std::string;
template <typename T>
void myprint(const char* format, T arg){
printf(format, arg);
}
template <>
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;
}