Given the following code, I was surprised that try_emplace
could not work out to use the default constructor demonstrated in the first line of the main function, instead complaining there is no matching function call to Element::Element(double, double)
. Have I misunderstood the way the compiler creates default constructors or the usage of try_emplace
? I can of course get this code to work by defining an all parameter ctors for Element
, but this seems redundant.
#include <string>
#include <map>
struct Element
{
double a;
double b;
};
int main(int argc, char** argv)
{
Element e {2.0, 3.0};
std::map<std::string, Element> my_map;
my_map.try_emplace("hello", 2.0, 3.0);
return 0;
}
Alternatively, you can opt to not define any user-defined ctors in Element
but rather use those that are still defined no matter what (unless explicitly deleted):
my_map.try_emplace("hello", Element{2.0, 3.0});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With