| 1 |
#include <stdexcept> |
| 2 |
#include <iostream> |
| 3 |
|
| 4 |
template<typename ...Params> |
| 5 |
void xprintf(std::string const &strFormat, Params ...parameters); |
| 6 |
|
| 7 |
void xprintf(char const *s) |
| 8 |
{ |
| 9 |
while (*s) |
| 10 |
{ |
| 11 |
if (*s == '%' && *(++s) != '%') |
| 12 |
throw std::runtime_error( |
| 13 |
"invalid format string: missing arguments"); |
| 14 |
std::cout << *s++; |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
template<typename T, typename ...Args> // 1 |
| 19 |
void xprintf(const char* s, T value, Args ...args) // 2 |
| 20 |
{ |
| 21 |
while (*s) |
| 22 |
{ |
| 23 |
if (*s == '%' && *(++s) != '%') // 6 |
| 24 |
{ |
| 25 |
std::cout << value; // 8 |
| 26 |
xprintf(*s ? ++s : s, args...); // 9 |
| 27 |
return; |
| 28 |
} |
| 29 |
std::cout << *s++; |
| 30 |
} |
| 31 |
throw std::logic_error("extra arguments provided to printf"); |
| 32 |
} |
| 33 |
|
| 34 |
int main() |
| 35 |
{ |
| 36 |
xprintf("hello %x worlds\n", 5); |
| 37 |
} |