Skip to content

Instantly share code, notes, and snippets.

@nmreadelf
Created January 12, 2023 07:12
Show Gist options
  • Save nmreadelf/b9a5a75e687375e1e706aaf0e41b386f to your computer and use it in GitHub Desktop.
Save nmreadelf/b9a5a75e687375e1e706aaf0e41b386f to your computer and use it in GitHub Desktop.
use c++ template implement printf
#include <iostream>
#include <string>
template <typename T> void printff(const char *s, const T &value) {
while (*s) {
if (*s == '%' && *++s != '%') {
std::cout << value;
}
std::cout << *s++;
}
}
template <typename T, typename... Args>
void printff(const char *s, const T &value, const Args &...args) {
while (*s) {
if (*s == '%' && *++s != '%') {
std::cout << value;
return printff(++s, args...);
}
std::cout << *s++;
}
}
int main() {
const char *msg = "The value of %s is about %g (unlesss you live in %s).\n";
printff(msg, "pi", 3.1415, std::string("Indiana"));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment