diff --git a/taglib/toolkit/tmap.h b/taglib/toolkit/tmap.h index 13229417..fc582eb7 100644 --- a/taglib/toolkit/tmap.h +++ b/taglib/toolkit/tmap.h @@ -28,6 +28,8 @@ #include #include +#include +#include #include "taglib.h" @@ -74,6 +76,11 @@ namespace TagLib { */ Map(const Map &m); + /*! + * Constructs a Map with the contents of the braced initializer list. + */ + Map(std::initializer_list> init); + /*! * Destroys this instance of the Map. */ @@ -195,6 +202,11 @@ namespace TagLib { */ Map &operator=(const Map &m); + /*! + * Replace the contents of the map with those of the braced initializer list + */ + Map &operator=(std::initializer_list> init); + /*! * Exchanges the content of this map by the content of \a m. */ diff --git a/taglib/toolkit/tmap.tcc b/taglib/toolkit/tmap.tcc index 532dd136..99115c1f 100644 --- a/taglib/toolkit/tmap.tcc +++ b/taglib/toolkit/tmap.tcc @@ -37,9 +37,13 @@ public: MapPrivate() = default; #ifdef WANT_CLASS_INSTANTIATION_OF_MAP MapPrivate(const std::map& m) : map(m) {} + MapPrivate(std::initializer_list> init) : map(init) {} + std::map map; #else MapPrivate(const std::map& m) : map(m) {} + MapPrivate(std::initializer_list> init) : map(init) {} + std::map map; #endif }; @@ -53,6 +57,12 @@ Map::Map() : template Map::Map(const Map &) = default; +template +Map::Map(std::initializer_list> init) : + d(std::make_shared>(init)) +{ +} + template Map::~Map() = default; @@ -180,6 +190,13 @@ T &Map::operator[](const Key &key) template Map &Map::operator=(const Map &) = default; +template +Map &Map::operator=(std::initializer_list> init) +{ + Map(init).swap(*this); + return *this; +} + template void Map::swap(Map &m) { diff --git a/tests/test_map.cpp b/tests/test_map.cpp index a5f46e78..2228eebd 100644 --- a/tests/test_map.cpp +++ b/tests/test_map.cpp @@ -35,6 +35,7 @@ class TestMap : public CppUnit::TestFixture CPPUNIT_TEST_SUITE(TestMap); CPPUNIT_TEST(testInsert); CPPUNIT_TEST(testDetach); + CPPUNIT_TEST(testBracedInit); CPPUNIT_TEST_SUITE_END(); public: @@ -67,6 +68,29 @@ public: CPPUNIT_ASSERT_EQUAL(99, m2["bob"]); } + void testBracedInit() + { + Map m1 { + {"ONE", 1}, + {"TWO", 2}, + {"THREE", 3} + }; + CPPUNIT_ASSERT_EQUAL(3, static_cast(m1.size())); + CPPUNIT_ASSERT(m1.contains("ONE") && m1["ONE"] == 1); + CPPUNIT_ASSERT(m1.contains("TWO") && m1["TWO"] == 2); + CPPUNIT_ASSERT(m1.contains("THREE") && m1["THREE"] == 3); + + Map m2 = { + {"FOUR", 4}, + {"FIVE", 5}, + {"SIX", 6} + }; + CPPUNIT_ASSERT_EQUAL(3, static_cast(m2.size())); + CPPUNIT_ASSERT(m2.contains("FOUR") && m2["FOUR"] == 4); + CPPUNIT_ASSERT(m2.contains("FIVE") && m2["FIVE"] == 5); + CPPUNIT_ASSERT(m2.contains("SIX") && m2["SIX"] == 6); + } + }; CPPUNIT_TEST_SUITE_REGISTRATION(TestMap);