From 85050aa2e61cfc3c29cd8b74c472df1dd8db588c Mon Sep 17 00:00:00 2001 From: Nikolay Rapotkin Date: Fri, 13 Mar 2020 11:20:24 +0300 Subject: [PATCH] Ability to join elements of std::initializer_list was added --- include/fmt/ranges.h | 24 ++++++++++++++++++++++++ test/ranges-test.cc | 6 ++++++ 2 files changed, 30 insertions(+) diff --git a/include/fmt/ranges.h b/include/fmt/ranges.h index a789a975..f8f9adb7 100644 --- a/include/fmt/ranges.h +++ b/include/fmt/ranges.h @@ -12,6 +12,7 @@ #ifndef FMT_RANGES_H_ #define FMT_RANGES_H_ +#include #include #include "format.h" @@ -358,6 +359,29 @@ FMT_CONSTEXPR tuple_arg_join join(const std::tuple& tuple, return {tuple, sep}; } +/** + \rst + Returns an object that formats `initializer_list` with elements separated by + `sep`. + + **Example**:: + + fmt::print("{}", fmt::join({1, 2, 3}, ", ")); + // Output: "1, 2, 3" + \endrst + */ +template +arg_join>, char> join( + std::initializer_list list, string_view sep) { + return join(std::begin(list), std::end(list), sep); +} + +template +arg_join>, wchar_t> join( + std::initializer_list list, wstring_view sep) { + return join(std::begin(list), std::end(list), sep); +} + FMT_END_NAMESPACE #endif // FMT_RANGES_H_ diff --git a/test/ranges-test.cc b/test/ranges-test.cc index ee6c4551..a729948d 100644 --- a/test/ranges-test.cc +++ b/test/ranges-test.cc @@ -70,6 +70,12 @@ TEST(RangesTest, JoinTuple) { EXPECT_EQ("4.0", fmt::format("{}", fmt::join(t4, "/"))); } +TEST(RangesTest, JoinInitializerList) { + EXPECT_EQ("1, 2, 3", fmt::format("{}", fmt::join({1, 2, 3}, ", "))); + EXPECT_EQ("fmt rocks !", + fmt::format("{}", fmt::join({"fmt", "rocks", "!"}, " "))); +} + struct my_struct { int32_t i; std::string str; // can throw