cpp_weekly icon indicating copy to clipboard operation
cpp_weekly copied to clipboard

piecewise_construct

Open lefticus opened this issue 3 years ago • 1 comments

lefticus avatar Jun 23 '22 00:06 lefticus

A question I hope you can address: Is there a best way to use emplace with piecewise_construct with nested containers to construct or insert into the inner container consistently, regardless of the initial contents of the containers? For example, say I want to efficiently emplace {2, "three"} into a contained map<int, string> that is inside another map<int, ...>, regardless of what the inner or outer maps already contain:

                std::map<int, std::map<int, std::string>> nested_map;

                nested_map.emplace(std::piecewise_construct,
                                   std::forward_as_tuple(1),
                                   std::forward_as_tuple(2, "three")); // does not compile

                nested_map.emplace(std::piecewise_construct,
                                   std::forward_as_tuple(1),
                                   std::forward_as_tuple(std::pair{2, "three"})); // does not compile

                nested_map.emplace(std::piecewise_construct,
                                   std::forward_as_tuple(1),
                                   std::forward_as_tuple()); // compiles, default constructs inner map

                nested_map.emplace(std::piecewise_construct,
                                   std::forward_as_tuple(1),
                                   std::forward_as_tuple(std::map<int, std::string>{{2, "three"}})); // compiles but presumably discards the passed inner map since the outer map key already exists

                nested_map.clear();
                nested_map.emplace(std::piecewise_construct,
                                   std::forward_as_tuple(1),
                                   std::forward_as_tuple(std::map<int, std::string>{{2, "three"}})); // compiles but presumably construct-moves the inner map rather than constructing in place, and can't be used to repeatedly emplace into the inner map

                nested_map.clear();
                nested_map[1].emplace(std::piecewise_construct,
                                      std::forward_as_tuple(2),
                                      std::forward_as_tuple("three")); // compiles but presumably default constructs the inner map before emplacing into it (the first time)

geoffthemedio avatar Aug 09 '22 09:08 geoffthemedio