Skip to content

Instantly share code, notes, and snippets.

@mumreg
Last active April 20, 2016 21:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mumreg/139d47092f0741b951319d6aeaa3ebe3 to your computer and use it in GitHub Desktop.
Save mumreg/139d47092f0741b951319d6aeaa3ebe3 to your computer and use it in GitHub Desktop.
Strings formating approach
#include <iostream>
#include <cstddef>
#include <tuple>
#include <utility>
#include <sstream>
#include <vector>
template <typename Tuple, typename F, std::size_t ...Indices>
void for_each_impl(Tuple&& tuple, F&& f, std::index_sequence<Indices...>) {
using swallow = int[];
(void)swallow{
(f(std::get<Indices>(std::forward<Tuple>(tuple))), int{})...
};
}
template <typename Tuple, typename F>
void for_each(Tuple&& tuple, F&& f) {
constexpr std::size_t N = std::tuple_size<std::remove_reference_t<Tuple>>::value;
for_each_impl(std::forward<Tuple>(tuple), std::forward<F>(f),
std::make_index_sequence<N>{});
}
template<typename ... Args>
std::string formatArgs(const std::string& fmt_str, const std::tuple<Args...>& args)
{
auto outStr = fmt_str;
auto stringArgs = std::vector<std::string>();
for_each(args, [&stringArgs](auto x) {
std::ostringstream os;
os << x;
stringArgs.emplace_back(os.str());
});
auto it = outStr.find("%1");
int count = 0;
while (it != std::string::npos)
{
if (count < stringArgs.size())
{
outStr.replace(it, 2, "");
outStr.insert(it, stringArgs[count]);
++count;
it = outStr.find("%" + std::to_string(count + 1));
}
else
{
break;
}
}
return outStr;
}
template<typename ... Args> void setText(const std::string& string, Args ... args)
{
std::cout << formatArgs(string, std::make_tuple(std::forward<Args>(args)...)) << std::endl;
}
int main(int argc, const char * argv[]) {
setText("Hello %1 %2 %3 Bye", 1, "Polly", 34.5f);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment