I am trying to get some C++ code originally written in Microsoft Visual Studio (VS) 2003 to compile under VS 2008 and I am having trouble finding an efficient solution to assigning a vector::iterator to the beginning of a char array. I know that iterators went from being a def开发者_JAVA百科ined as a simple pointer type (T*) to a class type between VS 2003 and VS 2005. Here is a simple example of what I am talking about:
typedef std::vector<char> CharContainer;
typedef CharContainer::iterator InputIt;
int FindNumMsgs( InputIt _inputIter, int _len );
int ProcessBufferForMsgs( char buf[], const size_t maxlen )
{
int numMsgs = FindNumMsgs( InputIt(buf), maxlen );
...
}
So, in VS 2003, this compiles and works with no problem (since iterators are defined as T*). In VS 2008, this errors with C2440 (function-style-cast) since I can no longer just assign the iterator with the buf pointer. What would I do to get this to work in VS 2008 now that iterators are a class type? I could copy the buffer into a vector, then pass in myVec.begin(), but I have to think that I can avoid this overhead.
The proper solution would be to template FindNumMsgs such that it can work with either iterators or pointers (since pointers can be used as iterators just fine). Something like this:
template <class T>
int FindNumMsgs(T it, int count) {
while(count--) {
// do whatever
it++;
}
return n;
}
If FindNumMsgs accepts char* as the first parameter, maybe you could just use a simple char* pointer:
int ProcessBufferForMsgs( char buf[], const size_t maxlen )
{
char* simpleIterator = buf;
int numMsgs = FindNumMsgs( simpleIterator, maxlen );
...
}
What's the signature of FindNumMsgs? If it takes a char* you can just replace InputIt(buf) with buf. If it doesn't, there's little you can do about it without changing FindNumMsgs.
Time to refactor. You need to change FindNumMsgs to take a (const?) char * as input, or maybe provide a second overloaded version. Better yet make it a templatized function that takes a begin/end pair of anything with iterator or pointer semantics.
加载中,请稍侯......
精彩评论