作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
根据 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/
我是一名优秀的程序员,十分优秀!