gpt4 book ai didi

c++ - vector> 到 vector> 的隐式转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:09 26 4
gpt4 key购买 nike

根据 this page您可以隐式转换 shared_ptr<Foo>shared_ptr<const Foo> .这很有道理。

但是,当我尝试转换 std::vector 时遇到错误包含 shared_ptr<Foo>到一个包含 shared_ptr<const Foo> 的.

有没有什么好的方法可以实现这种转化?

最佳答案

编号:std::vector<shared_ptr<Foo> >std::vector<shared_ptr<const Foo> >是不同的类型,因此您不能将一种类型的对象视为另一种类型的对象。

如果你真的需要 std::vector<shared_ptr<const Foo> > , 你可以很容易地用 shared_ptr 创建一个s 到与原始元素相同的元素:

std::vector<shared_ptr<Foo> > v;
std::vector<shared_ptr<const Foo> > cv(v.begin(), v.end());

但是,如果您根据迭代器编写代码,您应该不会有任何问题。也就是说,而不是使用

void f(const std::vector<shared_ptr<const Foo> >&);

// used as:
std::vector<shared_ptr<const Foo> > v;
f(v);

你应该使用

template <typename ForwardIterator>
void f(ForwardIterator first, ForwardIterator last);

// used as:
std::vector<shared_ptr<const Foo> > v;
f(v.begin(), v.end());

这样,函数f只需要它获得一系列可用作指向 const Foo 的指针的东西(或 shared_ptr<const Foo> s,如果函数假定范围包含 shared_ptr s)。

当函数采用范围而不是容器时,您将函数与底层数据分离:数据实际是什么或数据如何存储不再重要,只要您可以按照自己的方式使用它需要使用它。

关于c++ - vector<shared_ptr<Foo>> 到 vector<shared_ptr<const Foo>> 的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6040384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com