安全地将(shared_ptr 到对象的向量)转换为(shared_ptr 到常量对象的向量)
class A {};
typedef shared_ptr<const A*> AConstPtr;
typedef shared_ptr<A*> APtr;
vector<APtr> ptr;
const vector<AConstPtr>* foo()
{
return &ptr;
}
此代码无法编译,因为“没有从向量<
Aptr>
*到const向量<
AConstPtr>> * " 是否有办法在不创建新向量且不使用不安全的强制转换的情况下使这项工作正常进行?
我需要这个的原因是因为我有一个类在内部将列表存储为矢量<
APtr>
,但需要通过公开它的完全const版本它的界面。
class A {};
typedef shared_ptr<const A*> AConstPtr;
typedef shared_ptr<A*> APtr;
vector<APtr> ptr;
const vector<AConstPtr>* foo()
{
return &ptr;
}
This code does not compile, because "there is no implicit conversion from vector<
Aptr>
* to const vector<
AConstPtr>
* "
Is there anyway to make this work, without creating a new vector, and without using an unsafe cast?
The reason why I need this is because I have a class that stores a list internally as vector<
APtr>
, but needs to expose a completely const version of it through its interface.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于不同的
shared_ptr
不是相关类型,因此无法进行此类转换。首先,您真的确定需要公开存在共享指针的内部向量的实现细节吗?这确实会将您与该实现联系起来,并且在不破坏 API 的情况下不会对其进行更改。
使用 @Cubbi 的建议并让您的界面成为带有
begin
和end
方法的交互器怎么样?然后,您可以轻松地向外部客户端表示容器,而无需将自己绑定到vector
。There's no way to do such a conversion since different
shared_ptr
s aren't related types.First, are you really sure that you need to expose the implementation detail that there's an internal vector of shared pointers? That's really going to tie you to that implementation and it won't be subject to change without breaking API.
What about using @Cubbi's suggestion and having your interface be interators with
begin
andend
methods instead? Then you can easily represent a container to the outside clients without tying yourself tovector
.