投射向量<T>到向量<const T>

2022-01-23 00:00:00 constants c++

我有一个类型为 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.

相关文章