投射向量<T>到向量<const T> [英] Cast vector<T> to vector<const T>

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

问题描述

我有一个类型为 vector<T> 的成员变量(其中 T 是自定义类,但也可以是 int.)我有一个函数,我想从中返回指向该向量的指针,但我不希望调用者能够更改向量或其项.所以我希望返回类型是 const vector<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 vector 你不能修改容器,也不能修改容器中的任何元素.您不需要 const vector<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天全站免登陆