Consider this
void f(vector& p)
{
}
int main()
{
vector nonConstVec;
f(nonConstVec);
}
The followi
Others have already given the reason why the code you gave doesn't compile, but I have a different answer on how to deal with it. I don't believe there's any way to teach the compiler how to automatically convert the two (because that would involve changing the definition of std::vector). The only way around this annoyance is to do an explicit conversion.
Converting to a completely different vector is unsatisfying (wastes memory and cycles for something that should be completely identical). I suggest the following:
#include
#include
using namespace std;
typedef int T;
T a = 1;
T b = 2;
void f(vector& p)
{
for (vector::const_iterator iter = p.begin(); iter != p.end(); ++iter) {
cout << **iter << endl;
}
}
vector& constify(vector& v)
{
// Compiler doesn't know how to automatically convert
// std::vector to std::vector because the way
// the template system works means that in theory the two may
// be specialised differently. This is an explicit conversion.
return reinterpret_cast&>(v);
}
int main()
{
vector nonConstVec;
nonConstVec.push_back(&a);
nonConstVec.push_back(&b);
f(constify(nonConstVec));
}
I'm using reinterpret_cast to declare that the two things are the same. You SHOULD feel dirty after using it, but if you put it in a function by itself with a comment for those following you, then have a wash and try to continue on your way with a good conscience, though you will always (rightly) have that nagging worry about someone pulling the ground out from under you.