[PATCH] D73640: [SmallString] Add explicit conversion to std::string

Jonas Devlieghere via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Wed Jan 29 09:40:21 PST 2020


JDevlieghere created this revision.
JDevlieghere added reviewers: bkramer, cishida, MaskRay, Bigcheese.
Herald added a subscriber: dexonsmith.
Herald added a project: LLVM.

With the conversion between `StringRef` and `std::string` now being explicit, converting `SmallString`s becomes more tedious. This patch adds an explicit operator so you can write `std::string(Str)` instead of `Str.str().str()`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D73640

Files:
  llvm/include/llvm/ADT/SmallString.h
  llvm/unittests/ADT/SmallStringTest.cpp


Index: llvm/unittests/ADT/SmallStringTest.cpp
===================================================================
--- llvm/unittests/ADT/SmallStringTest.cpp
+++ llvm/unittests/ADT/SmallStringTest.cpp
@@ -96,6 +96,20 @@
   EXPECT_STREQ("abcabc", theString.c_str());
 }
 
+TEST_F(SmallStringTest, StringRefConversion) {
+  StringRef abc = "abc";
+  theString.assign(abc.begin(), abc.end());
+  StringRef theStringRef = theString;
+  EXPECT_EQ("abc", theStringRef);
+}
+
+TEST_F(SmallStringTest, StdStringConversion) {
+  StringRef abc = "abc";
+  theString.assign(abc.begin(), abc.end());
+  std::string theStdString = std::string(theString);
+  EXPECT_EQ("abc", theStdString);
+}
+
 TEST_F(SmallStringTest, Substr) {
   theString = "hello";
   EXPECT_EQ("lo", theString.substr(3));
Index: llvm/include/llvm/ADT/SmallString.h
===================================================================
--- llvm/include/llvm/ADT/SmallString.h
+++ llvm/include/llvm/ADT/SmallString.h
@@ -275,6 +275,9 @@
   /// Implicit conversion to StringRef.
   operator StringRef() const { return str(); }
 
+  // Explicit conversion to std::string.
+  explicit operator std::string() const { return str().str(); }
+
   // Extra operators.
   const SmallString &operator=(StringRef RHS) {
     this->clear();


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D73640.241196.patch
Type: text/x-patch
Size: 1284 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20200129/9d02498f/attachment-0001.bin>


More information about the llvm-commits mailing list