Использование C ++ 17 выражений фолда , to_string()
(вместо более тяжелых iostreams) и SFINAE :
#include <string>
#include <utility>
using std::to_string;
auto to_string(std::string s) noexcept { return std::move(s); }
template <class... T>
auto stringify(T&&... x)
-> decltype((std::string() + ... + to_string(x))) {
return (std::string() + ... + to_string(x));
}
Слияние преимуществ повсеместной реализации потоковых вставок с преимуществом to_string()
s, как правило, намного лучшей производительности, где она вообще работает:
#include <string>
#include <utility>
#include <sstream>
namespace detail {
using std::to_string;
auto to_string(std::string s) noexcept { return std::move(s); }
template <class... T>
auto stringify(int, T&&... x)
-> decltype((std::string() + ... + to_string(x))) {
return (std::string() + ... + to_string(x));
}
template <class... T>
auto stringify(long, T&&... x)
-> decltype((std::declval<std::ostream&>() << ... << x), std::string()) {
std::stringstream ss;
(ss << ... << x);
return ss.str();
}
}
template <class... T>
auto stringify(T&&... x)
-> decltype(detail::stringify(1, x...)) {
return detail::stringify(1, x...);
}