diff options
author | Derek Mauro <dmauro@google.com> | 2024-05-13 12:26:04 -0700 |
---|---|---|
committer | Copybara-Service <copybara-worker@google.com> | 2024-05-13 12:27:02 -0700 |
commit | 73841853760d6f86f5fe0372f17b2456874b6399 (patch) | |
tree | b1385f6b107afa8a5f134420079be9885da3810e /absl/strings/str_join_test.cc | |
parent | 692d9e568301b2c01a35b8da3c9915cef4055a4f (diff) | |
download | abseil-73841853760d6f86f5fe0372f17b2456874b6399.tar.gz abseil-73841853760d6f86f5fe0372f17b2456874b6399.tar.bz2 abseil-73841853760d6f86f5fe0372f17b2456874b6399.zip |
Add a `string_view` overload to `absl::StrJoin`
This allows users to pass a collection of string-like objects in an
`initializer_list` without having to convert everything to the same
type first.
`initializer_list` has the requirement that everything is copied in to
the list. For strings hitting the `string_view` overload avoids
unnecessary copies.
This may be a breaking change if `absl::StrJoin` has an explicit
template parameter, for example `absl::StrJoin<std::string>({foo,
"bar"});`. In this case, remove the explicit template parameter.
PiperOrigin-RevId: 633295575
Change-Id: Ie5f0860f409f639a27a58949842ec961e0b3bdeb
Diffstat (limited to 'absl/strings/str_join_test.cc')
-rw-r--r-- | absl/strings/str_join_test.cc | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/absl/strings/str_join_test.cc b/absl/strings/str_join_test.cc index 449f95be..cd52e11d 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<T> + // 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<T> + // 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"), "-")); |