variadic template is introduced in c++11. And I found the printf function can be replaced using it. However, cout is used in the implementation. I am wondering if it is poss
At GoingNative2012, Andrei Alexandrescu gave an implementation of a variadic safe_printf(). He uses a two-step approach. First, check the format specifiers; and second, normalize the arguments being passed. Because the implementation delegates to printf() with checked formatters and arguments, there is no std::cout in sight and hardly any runtime overhead (the exception path should not be taken often in regular code)
Code summary:
template
int safe_printf(const char * f, const Ts&... ts)
{
check_printf(f, normalizeArg(ts)...); // check format specifiers
return printf(f, normalizeArg(ts)...); // output with clean arguments
}
void check_printf(const char * f)
{
// checking is O(N) in length of format specifiers
for (; *f; ++f) {
if (*f != ’%’ || *++f == ’%’) continue;
throw Exc("Bad format");
}
}
// variadic check_print(const char*, T...) omitted, see slides
template
typename enable_if::value, long>::type
normalizeArg(T arg)
{
return arg;
}
// more overloads for float, T* and std::string omitted, see slides