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

前端 未结 5 892
后悔当初
后悔当初 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:04

    In C++17 you can use std::map::try_emplace, that uses std::piecewise_construct internally and doesn't look that cumbersome. It also takes a key as the first argument (instead of forwarding everything into std::pair::pair() like emplace does).

    #include 
    
    struct A {
        A() = default;
    };
    
    int main()
    {
        std::map map;
    
        map.emplace(std::piecewise_construct,
                    std::forward_as_tuple(10),
                    std::forward_as_tuple());
        // ...vs...
        map.try_emplace(10);
    }
    

    Live example.

提交回复
热议问题