From 67e070fe5aec035762706739ce46cbcaea2edbaa Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Wed, 7 Feb 2018 07:37:05 -0800 Subject: [PATCH] Make format work with C++17 std::string_view (#571) --- include/fmt/core.h | 27 +++++++++++++++++---------- test/format-test.cc | 5 ----- test/printf-test.cc | 2 +- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/include/fmt/core.h b/include/fmt/core.h index abdc4635..ba14258b 100644 --- a/include/fmt/core.h +++ b/include/fmt/core.h @@ -24,6 +24,12 @@ # define FMT_HAS_FEATURE(x) 0 #endif +#if defined(__has_include) +# define FMT_HAS_INCLUDE(x) __has_include(x) +#else +# define FMT_HAS_INCLUDE(x) 0 +#endif + #ifdef __GNUC__ # define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) #else @@ -137,8 +143,15 @@ Type(const Type &) FMT_DELETED; \ void operator=(const Type &) FMT_DELETED +#if (FMT_HAS_INCLUDE() && __cplusplus > 201402L) || \ + (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910) +# include +namespace fmt { using std::basic_string_view; } +#elif (FMT_HAS_INCLUDE() && __cplusplus >= 201402L) +# include +namespace fmt { using std::experimental::basic_string_view; } +#else namespace fmt { - /** \rst An implementation of ``std::basic_string_view`` for pre-C++17. It provides a @@ -180,15 +193,6 @@ class basic_string_view { const std::basic_string &s) FMT_NOEXCEPT : data_(s.c_str()), size_(s.size()) {} - /** - \rst - Converts a string reference to an ``std::string`` object. - \endrst - */ - std::basic_string to_string() const { - return std::basic_string(data_, size_); - } - /** Returns a pointer to the string data. */ const Char *data() const { return data_; } @@ -231,7 +235,10 @@ class basic_string_view { return lhs.compare(rhs) >= 0; } }; +} // namespace fmt +#endif +namespace fmt { using string_view = basic_string_view; using wstring_view = basic_string_view; diff --git a/test/format-test.cc b/test/format-test.cc index 792b4014..f8361fe1 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -137,11 +137,6 @@ TEST(StringViewTest, Ctor) { EXPECT_EQ(4u, string_view(std::string("defg")).size()); } -TEST(StringViewTest, ConvertToString) { - std::string s = string_view("abc").to_string(); - EXPECT_EQ("abc", s); -} - TEST(WriterTest, NotCopyConstructible) { EXPECT_FALSE(std::is_copy_constructible::value); } diff --git a/test/printf-test.cc b/test/printf-test.cc index e5dc413a..15003316 100644 --- a/test/printf-test.cc +++ b/test/printf-test.cc @@ -41,7 +41,7 @@ const unsigned BIG_NUM = INT_MAX + 1u; // Makes format string argument positional. std::string make_positional(fmt::string_view format) { - std::string s(format.to_string()); + std::string s(format.data(), format.size()); s.replace(s.find('%'), 1, "%1$"); return s; }