OXYGENHUB
◆ main openmsx / src / utils / join.hh
1.2 KiB · C++ · last changed chore(): initial commit 1 month ago source blame history raw
1
#ifndef JOIN_HH
2
#define JOIN_HH
3
4
#include "strCat.hh"
5
6
#include <iterator>
7
#include <string>
8
#include <utility>
9
10
namespace detail {
11
12
template<typename Collection, typename Separator>
13
class Joiner
14
{
15
public:
16
	Joiner(Collection&& col_, Separator&& sep_)
17
		: col(std::forward<Collection>(col_))
18
		, sep(std::forward<Separator>(sep_))
19
	{
20
	}
21
22
	[[nodiscard]] operator std::string() const
23
	{
24
		std::string result;
25
		auto first = std::begin(col);
26
		auto last  = std::end  (col);
27
		if (first != last) {
28
			result = strCat(*first);
29
			++first;
30
			while (first != last) {
31
				strAppend(result, sep, *first);
32
				++first;
33
			}
34
		}
35
		return result;
36
	}
37
38
private:
39
	Collection col;
40
	Separator sep;
41
};
42
43
} // namespace detail
44
45
// to enable strCat()
46
template<typename Col, typename Sep> struct strCatImpl::ConcatUnit<detail::Joiner<Col, Sep>>
47
	: public strCatImpl::ConcatViaString
48
{
49
	explicit ConcatUnit(const detail::Joiner<Col, Sep>& joiner)
50
		: strCatImpl::ConcatViaString(std::string(joiner)) {}
51
};
52
53
54
template<typename Collection, typename Separator>
55
[[nodiscard]] detail::Joiner<Collection, Separator> join(Collection&& col, Separator&& sep)
56
{
57
	return { std::forward<Collection>(col), std::forward<Separator>(sep) };
58
}
59
60
#endif