Custom STL container wrapper report weird compiler error
I have a C++ library (with over 50 source files) which uses a lot of STL routines with primary containers being list
and vector
. This has caused a huge code bloat and I would like to reduce the code bloat by creating another library which is essentially a wrapper
over the list
and vector
.
I basically need a wrapper around std::list
which works perfectly for the list container of any type.
Shown below is my list wrapper class.
template<typename T>
class wlist
{
private:
std::list<T> m_list;
public:
wlist();
typedef std::list<void*>::iterator Iterator;
typedef std::list<void*>::const_iterator CIterator;
unsigned int size () { return m_list.size(); }
bool empty () { return m_list.empty(); }
void pop_back () { m_list.pop_back(); }
void pop_front () { m_list.pop_front(); }
void push_front (const T& item) { m_list.push_front(item); }
void push_back (const T& item) { m_list.push_back(item); }
bool delete_item (void* item);
T& back () { return (m_list.empty()) ? NULL : m_list.back();}
T& front () { return (m_list.empty()) ? NULL : m_list.front();}
Iterator erase() { return m_list.erase(); }
Iterator begin() { return (Iterator) m_list.begin(); }
Iterator end() { return (Iterator) m_list.end(); }
};
File1.h:
cla开发者_开发问答ss label{
public:
int getPosition(void);
setPosition(int x);
private:
wlist<text> _elementText; // used in place of list<text> _elementText;
}
File2.h:
class image {
private:
void draw image() {
//Used instead of list<label*>::iterator currentElement = _elementText.begin();
wlist<label*>::iterator currentElement = _elementText.begin();
currentElement->getPosition(); // Here is the problem.
currentElement ++;
}
}
Invoking getPosition() bombs with the following error message:
error: request for member `getPosition' in `*(¤tElement)->std::_List_iterator<_Tp>::operator-> [with _Tp = void*]()', which is of non-class type `void*'
Type casting getPosition()
to label
type didn't work. Additionally my iterators are of type void*
.
I think the problem is that the line
currentElement->getPosition();
won't work because currentElement
is an iterator over void*
s, not label
s. Since iterators over some type T
act like T*
s, this means that your currentElement
iterator acts like a label**
, and so writing the above code is similar to writing
(*currentElement).getPosition();
Here, the problem should be a bit easier to see - *currentElement
is a label*
, not a label
, and so you can't use the dot operator on it.
To fix this, trying changing this code to
((label *)(*currentElement))->getPosition();
This dereferences the iterator and typecasts the void*
to get a label*
, then uses the arrow operator to call the getPosition()
function on the label
being pointed at.
Your iterator types seem to be declared in terms of std::list<void*>::iterator
. This doesn't sound right to me...
精彩评论