2009-11-16 71 views
8

創建一個可以與Qt foreach宏一起使用的定製容器的最小代碼量是多少?定製容器要求與Qt的foreach一起工作

我有這個迄今爲止

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

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

和我得到這個編譯器錯誤:當我嘗試編譯此

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 

MyList<int> mylst; 
    foreach(int num, mylst) 
    qDebug() << num; 
+5

注意的foreach創建容器的副本中找到,這不是一個大問題,因爲他們的類實現寫時複製,但它可能是你! – 2009-11-16 22:40:22

回答

10

我省略我使用的虛擬實現,但這爲我編譯:

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; 
}; 
1

作爲免責聲明,我不確定這是否可能。

查看qglobal.h中的foreach的定義。看起來您可能需要定義一個beginend方法。

在我的系統中,它在$QtInstallDir/src/corelib/global/qglobal.h