I am trying to do emplace_back
into a std::vector
, but could not find the right syntax to do it.
#i
emplace_back
does forward all arguments to a matching constructor of the member type. Now, std::map
has a initializer-list constructor, but it expects a list of std::pair
, i.e. std::pair
. push_back
is not a template, so it just expects one type and thus performs the conversion in place. That is, no type-deduction occurs here.
You would need to explicitly state that you want to have a std::pair
; the following should work:
#include
For the same reason, this does not compile:
v.emplace_back({std::pair(1,2),
std::pair(3,4)});
This is because, though a brace-enclosed list may yield an initializer-list, it doesn't have to. It can also be a constructor call or something like that. So, writing
auto l = {std::pair(1,2),
std::pair(3,4)};
yields an initializer list for l
, but the expression itself might be used in another way:
std::pair, std::pair> p =
{std::pair(1,2),
std::pair(3,4)}
This whole stuff gets a bit messy.
Basically, if you have an brace-enclosed-list, it may yield an initializer list or call a matching constructor. There are cases where the compiler is not able to determine which types are needed; emplace_back
is one of them (because of forwarding). In other cases it does work, because all types are defined in the expression. E.g.:
#include
#include
int main()
{
std::vector> v =
{{1,2},{3,4},{5,6}};
return 0;
}
Now the reason it doesn't work is that no type can be deduced. I.e. emplace_back
tries to deduce the name of the input types, but this is not possible, since a brace-enclosed-list has several types it can describe. Hence there is not a matching function call.