Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the std::piecewise_construct syntax work?

Tags:

c++

c++11

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

std::map<std::string, std::string> m;

// uses pair's 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 construction differently when piecewise_construct is used. Shouldn't it be: std::piecewise_construct(std::forward_as_tuple("c"), std::forward_as_tuple(10, 'c'))? How does it work with just commas, I don't see an overloaded comma operator or a special overload of emplace to handle piecewise and then variable args (as shown here).

like image 659
void.pointer Avatar asked Dec 01 '14 14:12

void.pointer


2 Answers

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

std::pair has the constructor taking std::piecewise_construct_t (the type of the std::piecewise_construct)

like image 96
milleniumbug Avatar answered Oct 26 '22 22:10

milleniumbug


map::emplace simply forwards its arguments to the constructor of pair<const K, V>. Pair has a constructor overload which takes piecewise_construct as the first argument.

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

like image 27
Dave S Avatar answered Oct 27 '22 00:10

Dave S