From 73bed45b7ab4ffeffbf463c08042c97c3094da3c Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Wed, 18 Jul 2018 14:12:10 -0700 Subject: [PATCH] Add support for types explicitly convertible to fmt::string_view --- include/fmt/core.h | 9 ++++++++- test/format-test.cc | 17 ++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/include/fmt/core.h b/include/fmt/core.h index f35bfc3a..c65709ac 100644 --- a/include/fmt/core.h +++ b/include/fmt/core.h @@ -672,10 +672,17 @@ inline typename std::enable_if< typed_value>::type make_value(const T &val) { return static_cast(val); } +template +inline typename std::enable_if< + std::is_constructible, T>::value, + typed_value>::type + make_value(const T &val) { return string_view(val); } + template inline typename std::enable_if< !convert_to_int::value && - !std::is_convertible>::value, + !std::is_convertible>::value && + !std::is_constructible::value, // Implicit conversion to std::string is not handled here because it's // unsafe: https://github.com/fmtlib/fmt/issues/729 typed_value>::type diff --git a/test/format-test.cc b/test/format-test.cc index d283d913..2b3ac5fa 100644 --- a/test/format-test.cc +++ b/test/format-test.cc @@ -1085,14 +1085,25 @@ TEST(FormatterTest, FormatStdStringView) { } #endif -struct ConvertibleToStringView { +struct implicitly_convertible_to_string_view { operator fmt::string_view() const { return "foo"; } }; -TEST(FormatterTest, FormatConvertibleToStringView) { - EXPECT_EQ("foo", format("{}", ConvertibleToStringView())); +TEST(FormatterTest, FormatImplicitlyConvertibleToStringView) { + EXPECT_EQ("foo", format("{}", implicitly_convertible_to_string_view())); } +// std::is_constructible is broken in MSVC until version 2015. +#if !FMT_MSC_VER || FMT_MSC_VER >= 1900 +struct explicitly_convertible_to_string_view { + explicit operator fmt::string_view() const { return "foo"; } +}; + +TEST(FormatterTest, FormatExplicitlyConvertibleToStringView) { + EXPECT_EQ("foo", format("{}", explicitly_convertible_to_string_view())); +} +#endif + FMT_BEGIN_NAMESPACE template <> struct formatter {