Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's not a complicated issue to make something similar to boost. Here's a class with just three functions, including the constructor, to replicate what boost did (almost).</p> <pre><code>template &lt;typename T, typename U> class create_map { private: std::map&lt;T, U> m_map; public: create_map(const T& key, const U& val) { m_map[key] = val; } create_map&lt;T, U>& operator()(const T& key, const U& val) { m_map[key] = val; return *this; } operator std::map&lt;T, U>() { return m_map; } }; </code></pre> <p>Usage:</p> <pre> std::map mymap = create_map&lt;int, int >(1,2)(3,4)(5,6); </pre> <p>The above code works best for initialization of global variables or static members of a class which needs to be initialized and you have no idea when it gets used first but you want to assure that the values are available in it.</p> <p>If say, you've got to insert elements into an existing std::map... here's another class for you.</p> <pre><code>template &lt;typename MapType&gt; class map_add_values { private: MapType mMap; public: typedef typename MapType::key_type KeyType; typedef typename MapType::mapped_type MappedType; map_add_values(const KeyType&amp; key, const MappedType&amp; val) { mMap[key] = val; } map_add_values&amp; operator()(const KeyType&amp; key, const MappedType&amp; val) { mMap[key] = val; return *this; } void to (MapType&amp; map) { map.insert(mMap.begin(), mMap.end()); } }; </code></pre> <p>Usage:</p> <pre><code>typedef std::map&lt;int, int&gt; Int2IntMap; Int2IntMap testMap; map_add_values&lt;Int2IntMap&gt;(1,2)(3,4)(5,6).to(testMap); </code></pre> <p>See it in action with GCC 4.7.2 here: <a href="http://ideone.com/3uYJiH" rel="noreferrer">http://ideone.com/3uYJiH</a></p> <p><strong>############### EVERYTHING BELOW THIS IS OBSOLETE #################</strong></p> <p><strong>EDIT</strong>: The <code>map_add_values</code> class below, which was the original solution I had suggested, would fail when it comes to GCC 4.5+. Please look at the code above for how to <strong>add</strong> values to existing map.</p> <pre><code> template&lt;typename T, typename U> class map_add_values { private: std::map&lt;T,U>& m_map; public: map_add_values(std::map&lt;T, U>& _map):m_map(_map){} map_add_values& operator()(const T& _key, const U& _val) { m_map[key] = val; return *this; } };</code></pre> <p>Usage:</p> <pre>std::map&lt;int, int> my_map; // Later somewhere along the code map_add_values&lt;int,int>(my_map)(1,2)(3,4)(5,6);</pre> <p>NOTE: Previously I used a <code>operator []</code> for adding the actual values. This is not possible as commented by dalle.</p> <p><strong>##################### END OF OBSOLETE SECTION #####################</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload