Skip to content

Commit 4c9b9a4

Browse files
committed
util: Enhance Join()
1 parent fe05dd0 commit 4c9b9a4

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/util/string.h

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,20 +30,28 @@ NODISCARD inline std::string TrimString(const std::string& str, const std::strin
3030
* @param separator The separator
3131
* @param unary_op Apply this operator to each item in the list
3232
*/
33-
template <typename T, typename UnaryOp>
34-
std::string Join(const std::vector<T>& list, const std::string& separator, UnaryOp unary_op)
33+
template <typename T, typename BaseType, typename UnaryOp>
34+
auto Join(const std::vector<T>& list, const BaseType& separator, UnaryOp unary_op)
35+
-> decltype(unary_op(list.at(0)))
3536
{
36-
std::string ret;
37+
decltype(unary_op(list.at(0))) ret;
3738
for (size_t i = 0; i < list.size(); ++i) {
3839
if (i > 0) ret += separator;
3940
ret += unary_op(list.at(i));
4041
}
4142
return ret;
4243
}
4344

45+
template <typename T>
46+
T Join(const std::vector<T>& list, const T& separator)
47+
{
48+
return Join(list, separator, [](const T& i) { return i; });
49+
}
50+
51+
// Explicit overload needed for c_str arguments, which would otherwise cause a substitution failure in the template above.
4452
inline std::string Join(const std::vector<std::string>& list, const std::string& separator)
4553
{
46-
return Join(list, separator, [](const std::string& i) { return i; });
54+
return Join<std::string>(list, separator);
4755
}
4856

4957
/**

0 commit comments

Comments
 (0)