铸造矢量< T>到向量< const T> [英] Cast vector<T> to vector<const T>

查看:141
本文介绍了铸造矢量< T>到向量< const T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型的向量< T>的成员变量(其中T是一个自定义类,但也可以是int)
有一个函数,我想要从这个向量返回一个指针,但我不想让调用者能够改变向量或它的项目。所以我想要的返回类型是 const向量< const T> *

I have a member variable of type vector<T> (where is T is a custom class, but it could be int as well.) I have a function from which I want to return a pointer to this vector, but I don't want the caller to be able to change the vector or it's items. So I want the return type to be const vector<const T>*

工作。编译器不断地抱怨T与const T不兼容。

None of the casting methods I tried worked. The compiler keeps complaining that T is not compatible with const T.

这里有一些代码演示了我想要做的事情;

Here's some code that demonstrates the gist of what I'm trying to do;

vector<int> a;
const vector<const int>* b = (const vector<const int>* ) (&a);

此代码不为我编译。

提前感谢!

推荐答案

如果你有一个 const向量< int> 您不能修改容器,也不能修改容器中的任何元素。你不需要一个 const向量< const int> 来实现这些语义。

If you have a const vector<int> you cannot modify the container, nor can you modify any of the elements in the container. You don't need a const vector<const int> to achieve those semantics.

这篇关于铸造矢量&lt; T&gt;到向量&lt; const T&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆