Skip to content

Instantly share code, notes, and snippets.

@en4bz
Last active February 21, 2017 02:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save en4bz/f07ef13706c3ae3a4fb2 to your computer and use it in GitHub Desktop.
Save en4bz/f07ef13706c3ae3a4fb2 to your computer and use it in GitHub Desktop.
sprintf with C++ variadic templates
#include <iostream>
#include <sstream>
#include <tuple>
template<class Tuple, std::size_t N>
struct TuplePrinter {
static void print(const std::string& fmt, std::ostream& os, const Tuple& t) {
const size_t idx = fmt.find_last_of('%');
TuplePrinter<Tuple, N-1>::print(std::string(fmt, 0, idx), os,t);
os << std::get<N-1>(t) << std::string(fmt, idx + 1);
}
};
template<class Tuple>
struct TuplePrinter<Tuple, 1>{
static void print(const std::string& fmt, std::ostream& os, const Tuple& t) {
const size_t idx = fmt.find_first_of('%');
os << std::string(fmt,0,idx) << std::get<0>(t) << std::string(fmt, idx +1);
}
};
template<class... Args>
std::string format(const std::string& fmt, Args&&... args) {
std::stringstream ss;
const auto t = std::make_tuple(std::forward<Args>(args)...);
TuplePrinter<decltype(t), sizeof...(Args)>::print(fmt, ss, t);
return ss.str();
}
int main() {
std::cout << format("% xyz %.", "Hello", "World") << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment