How to emplace object with no-argument constructor into std::map?

前端 未结 5 896
后悔当初
后悔当初 2020-12-14 05:40

I want to emplace an object into a std::map whose constructor does not take any arguments. However, std::map::emplace seems to require at least one

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 06:12

    You could explicitly create a pair and pass that to map::emplace, or use the piecewise construction constructor of std::pair.

    struct foo {};
    
    std::map m;
    
    m.emplace(std::pair(1, {}));
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple(2),
              std::forward_as_tuple());
    

    Live demo

提交回复
热议问题