views:

170

answers:

2

What is the bare minimum amount of code to create a custom container that would work with Qt foreach macro?

I have this so far

template< class T >
class MyList
{
public:
  class iterator
  {
  public:

  };
  class const_iterator
  {
  public:
    inline iterator& operator++ ()
    {
      return *this;
    }
  };
};

and I'm getting this compiler error:

4>.\main.cpp(42) : error C2100: illegal indirection
4>.\main.cpp(42) : error C2440: 'initializing' : cannot convert from 'MyList<T>::const_iterator' to 'int'
4>        with
4>        [
4>            T=int
4>        ]
4>        No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

when I try to compile this:

  MyList<int> mylst;
  foreach(int num, mylst )
    qDebug() << num;
+3  A: 

I've omitted the dummy implementations I used but this compiled for me:

template< class T >
class MyList
{
public:
    class const_iterator
    {
    public:
        const T& operator*();
        bool operator!=( const const_iterator& ) const;
        const_iterator& operator++();
    };

    const_iterator begin() const;
    const_iterator end() const;
};
Troubadour
+1  A: 

As a disclaimer I am not sure if this is possible.

Check out the definition of foreach in qglobal.h. It looks like you may need to define a begin and end methods.

On my system it is found at $QtInstallDir/src/corelib/global/qglobal.h

Jesse