diff --git a/absl/strings/str_join.h b/absl/strings/str_join.h index 6a92c0f53ac..badc944a0cf 100644 --- a/absl/strings/str_join.h +++ b/absl/strings/str_join.h @@ -247,12 +247,20 @@ std::string StrJoin(const Range& range, absl::string_view separator, return strings_internal::JoinRange(range, separator, fmt); } -template +template ::value>::type> std::string StrJoin(std::initializer_list il, absl::string_view separator, Formatter&& fmt) { return strings_internal::JoinRange(il, separator, fmt); } +template +inline std::string StrJoin(std::initializer_list il, + absl::string_view separator, Formatter&& fmt) { + return strings_internal::JoinRange(il, separator, fmt); +} + template std::string StrJoin(const std::tuple& value, absl::string_view separator, Formatter&& fmt) { @@ -269,9 +277,14 @@ std::string StrJoin(const Range& range, absl::string_view separator) { return strings_internal::JoinRange(range, separator); } -template -std::string StrJoin(std::initializer_list il, - absl::string_view separator) { +template ::value>::type> +std::string StrJoin(std::initializer_list il, absl::string_view separator) { + return strings_internal::JoinRange(il, separator); +} + +inline std::string StrJoin(std::initializer_list il, + absl::string_view separator) { return strings_internal::JoinRange(il, separator); } diff --git a/absl/strings/str_join_test.cc b/absl/strings/str_join_test.cc index 449f95be3ed..cd52e11d13d 100644 --- a/absl/strings/str_join_test.cc +++ b/absl/strings/str_join_test.cc @@ -428,6 +428,42 @@ TEST(StrJoin, InitializerList) { } } +TEST(StrJoin, StringViewInitializerList) { + { + // Tests initializer_list of string_views + std::string b = "b"; + EXPECT_EQ("a-b-c", absl::StrJoin({"a", b, "c"}, "-")); + } + { + // Tests initializer_list of string_views with a non-default formatter + TestingParenFormatter f; + std::string b = "b"; + EXPECT_EQ("(a)-(b)-(c)", absl::StrJoin({"a", b, "c"}, "-", f)); + } + + class NoCopy { + public: + explicit NoCopy(absl::string_view view) : view_(view) {} + NoCopy(const NoCopy&) = delete; + operator absl::string_view() { return view_; } // NOLINT + private: + absl::string_view view_; + }; + { + // Tests initializer_list of string_views preferred over initializer_list + // for T that is implicitly convertible to string_view + EXPECT_EQ("a-b-c", + absl::StrJoin({NoCopy("a"), NoCopy("b"), NoCopy("c")}, "-")); + } + { + // Tests initializer_list of string_views preferred over initializer_list + // for T that is implicitly convertible to string_view + TestingParenFormatter f; + EXPECT_EQ("(a)-(b)-(c)", + absl::StrJoin({NoCopy("a"), NoCopy("b"), NoCopy("c")}, "-", f)); + } +} + TEST(StrJoin, Tuple) { EXPECT_EQ("", absl::StrJoin(std::make_tuple(), "-")); EXPECT_EQ("hello", absl::StrJoin(std::make_tuple("hello"), "-"));