Initialize static std::map with unique_ptr as value

前端 未结 3 978
执笔经年
执笔经年 2021-01-18 06:11

How can one initialize static map, where value is std::unique_ptr?

static void f()
{
    static std::map&         


        
3条回答
  •  离开以前
    2021-01-18 06:50

    The Problem is that constructing from std::initializer-list copies its contents. (objects in std::initializer_list are inherently const). To solve your problem: You can initialize the map from a separate function...

    std::map> init(){
        std::map> mp;
        mp[0] = std::make_unique();
        mp[1] = std::make_unique();
        //...etc
        return mp;
    }
    

    And then call it

    static void f()
    {
        static std::map> mp = init();
    }
    

    See it Live On Coliru

提交回复
热议问题