In the printMessage if you access the vector of a constant class using the index it works fine, but not with the the iterator (*itr). If the iterator is declared as constant_iterator then it works fine.
Why?
In both cases I am reading the data and not modifying the vector. Can someone shed some light?
#include <iostream>
#include <vector>
#include <sstream>
//Set this define to enable the block to compile.
#define WILL_WORK 1
#define WILL_NOT_WORK !WILL_WORK
class TestMessage
{
public:
TestMessage(){};
typedef std::vector<int> TestVec;
typedef std::vector<int>::iterator TestItr;
//The const iterator will work
//typedef std::vector<uint32_t>::const_iterator TestItr;
typedef std::vector<int>::size_type TestSize;
TestVec m_testVector;
};
void printMessage(const TestMessage & tmessage)
{
std::ostringstream asciiMessage;
asciiMessage << tmessage.m_testVector.size() << ",";
#if WILL_NOT_WORK
//This will not work
// MS Visual Studio
// error C2440: 'initializing' : cannot convert from
// 'std::_Vector_const_iterator<_Ty,_Alloc>' to
// 'std::_Vector_iterator<_Ty,_Alloc>'
// GCC
// error: conversion from
// '__gnu_cxx::__normal_iterator<const int*,
// std::vector<int, std::allocator<int> > >'
// to non-scalar type
// '__gnu_cxx::__normal_iterator<int*,
// std::vector<int, std::allocator<int> > >'
// requested
for (TestMessage::TestItr itr = tmessage.m_testVector.begin();
itr != tmessage.m_testVector.end();
++itr)
{
asciiMessage << *itr;
}
#endif
#if WILL_WORK
// This will work
for(TestMessage::TestSize index = 0;
index < tmessage.m_testVector.size();
++index)
{
asciiMessage << tmessage.m_testVector[index] << ",";
}
#endif
asciiMessage << std::endl;
std::cout << asciiMessage.str();
}
int main()
{
TestMessage message;
message.m_testVector.push_back(10);
message.m_testVector.push_back(20);
message.m_testVector.push_back(30);
message.m_testVector.push_back(40);
printMessage(message);
return 0;
}