Created
January 12, 2023 07:12
-
-
Save nmreadelf/b9a5a75e687375e1e706aaf0e41b386f to your computer and use it in GitHub Desktop.
use c++ template implement printf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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