Created
July 13, 2018 19:56
-
-
Save jdiego/ecfe001f5d7f81336e171b2d68a9014c to your computer and use it in GitHub Desktop.
A analog implementation of Python's 'separator'.join() in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage: std::cout << " "_join("Hello", "World") << std::endl; | |
#include <string_view> | |
#include <string> | |
#include <tuple> | |
#include <iostream> | |
class Joinit | |
{ | |
public: | |
Joinit(std::string_view sv): join(sv) | |
{} | |
template<typename... Args> | |
auto operator()(Args&&... args) | |
{ | |
auto svs = std::make_tuple(std::string_view{std::forward<Args>(args)}...); | |
auto len = [](auto... args){ return (args.length() + ...);}; | |
std::string buffer; | |
buffer.reserve(std::apply(len, svs)); | |
auto joined_string = [&](auto... args){ return concat(buffer, args...); }; | |
return std::apply(joined_string, svs); | |
} | |
private: | |
auto& concat(std::string& str, std::string_view sv) | |
{ | |
return str += sv; | |
} | |
template<typename... Args> | |
auto& concat(std::string& str, std::string_view sv, Args... args) | |
{ | |
return concat(str.append(sv).append(this->join), args...); | |
} | |
std::string join; | |
}; | |
auto operator"" _join(const char* buffer, size_t size) | |
{ | |
return Joinit{{buffer, size}}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment