Info
-
Did you know that C++23 added spanstream - A strstream replacement using span as buffer?
Example
#include <spanstream>
int main() {
char output[30]{};
std::ospanstream os{std::span<char>{output}};
os << 10 << 20 << 30;
auto const sp = os.span();
std::cout << sp.size(); // prints 6
std::cout << std::string(sp.data(),sp.size()); // prints 102030
}
Puzzle
- Can you implement
strcat
using spanstream?
[[nodiscard]] constexpr auto strcat(auto...); // TODO
int main() {
using namespace boost::ut;
"strcat"_test = [] {
expect(std::string{""} == strcat());
expect(std::string{"1"} == strcat(1));
expect(std::string{"1"} == strcat("1"));
expect(std::string{"42"} == strcat("42"));
expect(std::string{"42"} == strcat("4", 2));
expect(std::string{"123"} == strcat(1, "2", 3));
};
}
Solutions
[[nodiscard]] constexpr auto strcat(auto&&... args) {
char buf[256]{};
std::ospanstream oss{std::span{buf}};
((oss << args), ...);
const auto span = oss.span();
return std::string{span.data(), span.size()};
}