I'm looking to get some feedback on a small printf
-like function I wrote that provides simplified behavior similar to boost::format
:
#ifndef EXT_FORMAT_HPP__
#define EXT_FORMAT_HPP__
// ext::format
// Implements a variadic printf-like function providing behavior similar to
// boost::format
#include <regex>
#include <sstream>
#include <string>
#include <utility>
namespace {
inline std::string format_helper(
const std::string &string_to_update,
const size_t) {
return string_to_update;
}
template <typename T, typename... Args>
inline std::string format_helper(
const std::string &string_to_update,
const size_t index_to_replace,
T &&val,
Args &&...args) {
std::regex pattern{"%" + std::to_string(index_to_replace)};
std::string replacement_string{(std::ostringstream{} << val).str()};
return format_helper(
std::regex_replace(string_to_update, pattern, replacement_string),
index_to_replace + 1,
std::forward<Args>(args)...);
}
} // namespace
namespace ext {
template <typename... Args>
inline std::string format(const std::string &format_string, Args &&...args) {
return format_helper(format_string, 1, std::forward<Args>(args)...);
}
} // namespace ext
#endif
Usage example:
#include "format.hpp"
#include <iostream>
struct foo {
int value;
foo(int val) : value{val} {
}
};
std::ostream &operator<<(std::ostream &os, const foo &f) {
os << "foo(" << f.value << ")";
return os;
}
int main() {
double tmp = 37.382;
std::cout << ext::format("%1 + %2 * %1 = %3", 5, tmp, 5 + tmp * 5) << std::endl;
// Support user defined types provided the appropriate operator<< overload is defined.
foo a_foo(55);
std::cout << ext::format("Here is a foo constructed with 55: %1", a_foo) << std::endl;
};
This is not written to replace boost::format
; it's intended to be used as a header-only include with a very limited scope. As currently written, it is possible to supply too few or too many arguments to the parameter pack. Passing too few arguments will return a string that still has format specifiers. Passing excess arguments are simply ignored and you pay the price of excess calls to std::regex_replace
, which will do nothing. With that in mind, I'm looking for any and all feedback.
format_helper
for clarity rather than trying to squeeze everything into the return call. I also renamed variables to be more descriptive and reduced all line lengths to be within 80 characters. \$\endgroup\$