Skip to content

Instantly share code, notes, and snippets.

@kantoniak
Last active April 15, 2023 06:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kantoniak/9d9036d72f99650c946e0b2245dce92a to your computer and use it in GitHub Desktop.
Save kantoniak/9d9036d72f99650c946e0b2245dce92a to your computer and use it in GitHub Desktop.
Variadic templates example: simple logger
#include <chrono>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
using std::chrono::system_clock;
template <typename... Args>
void log(const char* format, Args... args) {
string formatAsString = "[%s] ";
formatAsString += format;
formatAsString += "\n";
const time_t currentTime = system_clock::to_time_t(system_clock::now());
printf(formatAsString.c_str(), strtok(ctime(&currentTime), "\n"), args...);
}
int main() {
log("Example 4: Simple logger");
log("Test message %d", 1);
log("Multiple elements %d, %.3f", 10, 152.39798);
log("IO Error: Could not load file %s", "hello_variadic.txt");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment