Last active
February 21, 2017 02:37
-
-
Save en4bz/f07ef13706c3ae3a4fb2 to your computer and use it in GitHub Desktop.
sprintf with C++ variadic templates
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 <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