How does the std :: piecewise_construct syntax work?

I am a little confused regarding std::piecewise_construct when used with std::map . Example:

 std::map<std::string, std::string> m; // uses pair piecewise constructor m.emplace(std::piecewise_construct, std::forward_as_tuple("c"), std::forward_as_tuple(10, 'c')); 

I'm not sure how emplace() knows how to handle this type of construct differently when piecewise_construct used. Shouldn't it be: std::piecewise_construct(std::forward_as_tuple("c"), std::forward_as_tuple(10, 'c')) ? As this only works with commas, I don’t see an overloaded comma operator or a special emplace overload to handle piecewise and then args variables (as shown here ).

+5
source share
2 answers

std::map::emplace directly calls the constructor with arguments passed to emplace (forwarding them) of type std::map<std::string, std::string>::value_type (which is typedef before std::pair<const std::string, std::string> ).

std::pair has a constructor that takes std::piecewise_construct_t (type std::piecewise_construct )

+6
source

map::emplace simply translates its arguments into the constructor pair<const K, V> . The couple has a constructor overload that takes piecewise_construct as the first argument.

See http://en.cppreference.com/w/cpp/utility/pair/pair constructor # 6

+3
source

Source: https://habr.com/ru/post/1208050/


All Articles