首页 > 解决方案 > 使用初始化列表初始化 unique_ptr 的容器,继续

问题描述

我想初始化std::vector's 和std::map'sstd::unique_ptr<T>的。在我的情况下,T是固定的。在此示例中,我假设T= int,尽管实际上它是一个基类,从中派生了许多其他类。

我一直在研究中给出的答案:

https://stackoverflow.com/a/46771893/4875652

我还没有设法让它为这个std::map案子工作。

以下作品:

#include <memory>
#include <vector>

struct movable_il {
  mutable iptr t;
  operator iptr() const&& { return std::move(t); }
  movable_il( iptr&& in ): t(std::move(in)) {}
};

std::vector<iptr> vector_from_il( std::initializer_list<movable_il> il ) {
  return std::vector<iptr>( std::make_move_iterator(il.begin()), std::make_move_iterator(il.end()) );
}

int main()
{
    auto lol = vector_from_il({iptr{new int{3}}});

   return 0;
}

但是,以下内容不会:

#include <memory>
#include <map>
#include <utility>

using iptr = std::unique_ptr<int>;

struct movable_il {
  mutable std::pair<std::string, iptr> t;
  operator std::pair<std::string, iptr>() const&& { return std::move(t); }
  movable_il( std::pair<std::string, iptr>&& in ): t(std::move(in)) {}
};

std::map<std::string, iptr> container_from_il( std::initializer_list< movable_il> il ) {
  return std::map<std::string, iptr>( std::make_move_iterator(il.begin()), std::make_move_iterator(il.end()) );
}

int main()
{
    auto lol = container_from_il({std::pair<std::string, iptr>{"a", iptr{new int{3}}}});

   return 0;
}

有任何想法吗?

更新:

我设法得到的最简单的工作示例,它与原始代码尽可能相似,不使用模板,是这样的:

#include <iostream>
#include <map>
#include <memory>
#include <utility>

struct movable_pair {
  using first_type = std::string;
  using second_type = std::unique_ptr<int>;
  using pair_type = std::pair<const first_type, second_type>;
  first_type first;
  mutable second_type second;
  operator pair_type() const && { return {first, std::move(second)}; }
  movable_pair(pair_type &&in): first{in.first}, second{std::move(in.second)} {}
};

auto map_from_il(std::initializer_list<movable_pair> il) {
  return std::map<std::string, std::unique_ptr<int>>(std::make_move_iterator(il.begin()),
                                                     std::make_move_iterator(il.end()));
}

// Main function
int main() {
  using iptr = std::unique_ptr<int>;
  auto lol = map_from_il({{{"a", iptr{new int{3}}}}, {{"b", iptr{new int{2}}}}});

  // Small print-out to check we inserted the correct elements :)
  for (auto &l : lol) {
    std::cout << l.first << " " << *l.second << std::endl;
  }

  return 0;
}

感谢用户 Banan 的帮助,特别是找出所需的额外一对花括号。

标签: c++

解决方案


据我所知,主要问题是您需要使pair' 可移动。这是由类完美完成的movable_il,但现在你在尝试map从这些中构造 the 时遇到了麻烦,因为firstandsecond成员没有为movable_il.

由于您无论如何都在尝试map从迭代器构造,我不认为您会看到自己进行迭代并手动插入元素会影响性能。我已经基于此制定了解决方案。这不是最漂亮的解决方案,但它会完成这项工作。

此外,我有一些问题让编译器Tpair“初始化列表”中推断出正确的类型,因此我制作了一个小的帮助函数movable_pair来创建这些,在这种情况下编译器没有问题。

#include <memory>
#include <map>
#include <utility>
#include <iostream>
#include <vector>

// Wrapper class to make type T "movable"
template<class T>
struct movable_il 
{
   mutable T t;
   operator T() const&& { return std::move(t); }
   movable_il( T&& in ): t(std::move(in)) {}

   T get() const { return std::move(t); }
};

// Some template magic to deduce the correct value_type 
// ( not really needed for this example as we are mostly interested in maps )
template<class VT>
struct fix_vt 
{
  using type = VT;
};

template<class VT>
using fix_vt_t = typename fix_vt<VT>::type;

template<class VT> struct fix_vt<const VT> :  fix_vt<VT>  {};

template<class K, class V>
struct fix_vt< std::pair<K,V> >
{
   using type = std::pair<
      typename std::remove_cv<K>::type,
      typename std::remove_cv<V>::type
   >;
};

// Create map from initializer list of movable T (pairs)
template<class C, class T = fix_vt_t<typename C::value_type> >
auto map_from_il(std::initializer_list< movable_il<T> > il)
{
   using map_type = C;
   auto map = map_type{};

   // Loop over il list and insert each element into the map
   for(auto&& entry : il)
   {
       map.insert(std::move(entry.get())); // We get the pair from the movable class and insert it by moving
   }

   return map;
}

// Helper function to create movable pair
template<class First, class Second>
auto movable_pair(First&& f, Second&& s)
{
   using pair_type = std::pair<First, Second>;
   return movable_il<pair_type>{ pair_type{ std::forward<First>(f), std::forward<Second>(s) } };
}

// Main function
int main()
{
   using iptr = std::unique_ptr<int>;
   using key_type   = std::string;
   using value_type = iptr;

   using map_type    = std::map<key_type, value_type>;

   auto lol = map_from_il<map_type>({ movable_pair("a", iptr{ new int {3} } ), movable_pair("b", iptr{ new int {2} }) });

   // Small print-out to check we inserted the correct elements :)
   for(auto& l : lol)
   {
      std::cout << l.first << " " << *l.second << std::endl;
   }

   return 0;
}

免责声明:我只用 GCC 8.1.0 对此进行了测试(但我不认为使用其他编译器会出现任何问题)。

更新:如果您在将对传递给时放入额外的{和集合,则代码在不使用辅助函数的情况下编译。}map_from_ilmovable_pair

auto lol = map_from_il<map_type>({ { {"a", iptr{ new int {3} } } }, { {"b", iptr{ new int {2} } } } });

更新 2:如果将以下构造函数添加到movable_il,则代码也可以编译而无需额外的{and }

template<class... U>
movable_il( U&&... in): t{std::forward<U>(in)...} {}

有了这个,你可以写:

auto lol = map_from_il<map_type>({ {"a", iptr{ new int {3} } }, {"b", iptr{ new int {2} } } });

推荐阅读