c++ - 将 shared_ptr 的集合转换为 weak_ptr 的集合

标签 c++ templates c++11 c++14

我很想找到一种方法来自动将可转换类型的容器相互转换。

例如,我希望它存在:

template<typename Collection, typename T>
Collection<std::weak_ptr<T> > convert(const Collection<std::shared_ptr<T> > &c){
    Collection<std::weak_ptr<T> > l;
    for (auto &e : c) l.push_back(e);
    return l;
}

我实际上想从参数类型中移除一层实例化模板,并使用不同的模板类型重新实例化它。

更理想的是,我可以编写一个更通用的转换函数;即不假设 push_back 的存在并且不专门用于 shared_ptr 转换为 weak_ptr 的情况。

有人知道这是否可行吗?

最佳答案

此函数存在并称为 std::copy

 Collection1 a;
 Collection2 b;

 std::copy(std::begin(a), std::end(a), std::back_inserter(b));

这适用于任何集合,只要为目标容器定义了 std::back_inserter 并且相应的元素是可转换的。

如果你需要在没有 back_inserter 的情况下支持某些东西,你需要为 std::copy 提供你自己的迭代器,并确保它适用于你的容器。

如果你想保持集合的“类型”并且只是交换模板参数,你可以使用这个:

template <template<typename> class OutPtr,
          template<typename> class InPtr,
          template<typename, typename> class Coll,
          typename Elem, typename Alloc>
auto transform_ptr_collection(const Coll<InPtr<Elem>, Alloc>& in) ->
                          Coll<OutPtr<Elem>, Alloc>
{
  return Coll<OutPtr<Elem>, Alloc>(std::begin(in), std::end(in));
}

// call it

suto out = transform_ptr_collection<std::weak_ptr>(vector_of_shared_ptr);

但我不会推荐它。首选迭代器接口(interface)而不是集合接口(interface),它们更通用且更易于使用。

关于c++ - 将 shared_ptr 的集合转换为 weak_ptr 的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467028/

相关文章:

c++ - 挂接 Windows API 函数使应用程序崩溃

c++ - 有没有办法在 QMenu 中有多个列?

c++ - 模板的自定义迭代器

c++ - `const T` 和 `T` 在采用嵌套类型时没有区别吗?

c++ - 错误 : reference to overloaded function could not be resolved; did you mean to call it?

c++ - 前向声明问题

c++ - 如果我不设置 EPOLLOUT 事件并直接调用 write() 函数会发生什么?

html - CSS 图像不显示 Wordpress

c++ - STL的copy函数的效率

c++ - 在特化的情况下,检查的保护参数包是否会导致格式错误的程序?