Skip to content

Latest commit

 

History

History
64 lines (46 loc) · 1.48 KB

360.md

File metadata and controls

64 lines (46 loc) · 1.48 KB
Info

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
}

https://godbolt.org/z/3Te1aPe1d

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));
    };
}

https://godbolt.org/z/75cMqdKx1

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()};
}

https://godbolt.org/z/z5bn7vq3x