Reputation: 10647
How can I cast vector<int>
to const vector<const int>
?
I've tried static_cast<const vector<const int>>(array)
and using the value without a cast. Neither compiled.
Upvotes: 2
Views: 7282
Reputation: 206577
You cannot cast a std::vector<int>
to const std::vector<const int>
.
Besides, it does not make sense to use a std::vector<const int>
at all. It doesn't give you any more safety than a const std::vector<int>
.
Not only that, C++ does not allow construction of std::vector<const T>
. See Does C++11 allow vector<const T>? for more info.
Upvotes: 3
Reputation: 2269
You cannot change the type of the elements of the vector, but you can change the type of the vector to const std::vector<int>
which will prevent making changes to the vector.
#include <vector>
int main()
{
std::vector<int> v1;
v.push_back(1);
v.push_back(2);
v.push_back(3);
const std::vector<int>& v2 = v1;
v2.push_back(4); // Causes an error
v2[0] = 4; // Causes an error
return 0;
}
Upvotes: 1