Skip to content

Commit

Permalink
fixed std::string builder
Browse files Browse the repository at this point in the history
  • Loading branch information
jm4R committed Oct 23, 2019
1 parent 5d40f2e commit 3479cde
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
34 changes: 34 additions & 0 deletions include/fast_strcat/string_builder.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <iostream>
#include <string_view>
#include <tuple>
#include <string>

template<typename... Args>
struct string_builder
{
std::tuple<Args&...> vals;

template <typename T>
constexpr auto operator<<(T& v) && -> string_builder<Args..., T>
{
return {std::tuple_cat(vals, std::tuple<T&>{v})};
}

constexpr operator std::string() &&
{
auto len = std::size_t{0};
std::apply([&](auto&... x){ (len += ... += std::string_view{x}.length()); } , vals);

auto res = std::string{};
res.reserve(len);

std::apply([&](auto&... x){ (res += ... += x); } , vals);

return res;
}
};

constexpr auto build_string()
{
return string_builder<>{};
}
5 changes: 5 additions & 0 deletions test/main.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
#include <fast_strcat/strcat.hpp>
#include <fast_strcat/string_builder.hpp>

#include <cassert>

int main()
{
std::string test2 = "test2";
const char* test4 = "test4";
std::string test = build_string() << "test1 " << test2 << " test3 " << test4;
assert(test == "test1 test2 test3 test4");
return 0;
}

0 comments on commit 3479cde

Please sign in to comment.