Initialize static std::map with unique_ptr as value

前端 未结 3 1008
执笔经年
执笔经年 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:26

    Writing bespoke crestion code seems boring and gets in the way of clarity.

    Here is reasonably efficient generic container initialization code. It stores your data in a temporary std::array like an initializer list does, but it moves out instead of making it const.

    The make_map takes an even number of elements, the first being key the second value.

    template
    struct make_container_t{
      std::array elements;
      template
      operator Container()&&{
        return {
          std::make_move_iterator(begin(elements)),
          std::make_move_iterator(end(elements))
        };
      }
    };
    template
    make_container_t
    make_container( E0 e0, Es... es ){
      return {{{std::move(e0), std::move(es)...}}};
    }
    
    namespace details{
      template
      make_container_t,sizeof...(Is)>
      make_map( std::index_sequence, std::tuple ts ){
        return {{{
          std::make_pair(
            std::move(std::get(ts)),
            std::move(std::get(ts))
          )...
        }}};
      }
    }
    template
    auto make_map( Es... es ){
      static_assert( !(sizeof...(es)&1), "key missing a value?  Try even arguments.");
      return details::make_map(
        std::make_index_sequence{},
        std::tie( es... )
      );
    }
    

    This should reduce it to:

    static std::map> bob = 
      make_map(0, std::make_unique());
    

    ... barring typos.

    Live example.

提交回复
热议问题