Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emplace and default constructors [duplicate]

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;
}
like image 565
Madden Avatar asked Aug 21 '18 10:08

Madden


1 Answers

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});
like image 52
bipll Avatar answered Oct 06 '22 01:10

bipll