I am trying to do emplace_back
into a std::vector
, but could not find the right syntax to do it.
#include
push_back
works here, but not emplace_back
. How can I get emplace_back
working?
Answer
One can achieve that using a helper function as follows:
#include
The problem was when we write:
v.emplace_back({{1,2}}); // here {{1,2}} does not have a type.
the compiler is not able to deduce the type of the argument, and it can't decide which constructor to call.
The underlying idea is that when you write a function like
template
void f(T) {}
and use it like
f( {1,2,3,4} ); //error
you will get compiler error, as {1,2,3,4} does have a type.
But if you define your function as
template
void f(std::initializer_list) {}
f( {1,2,3,4} );
then it compiles perfectly.
No comments:
Post a Comment