【问题标题】:Custom container requirement to work with Qt's foreach使用 Qt 的 foreach 的自定义容器要求
【发布时间】:2009-11-16 21:57:38
【问题描述】:

创建可与 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;

【问题讨论】:

  • 请注意,foreach 创建容器的副本,这没什么大不了的,因为它们的类实现了写入时复制,但它可能适合您!

标签: qt foreach containers


【解决方案1】:

我省略了我使用的虚拟实现,但这是为我编译的:

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

【讨论】:

    【解决方案2】:

    作为免责声明,我不确定这是否可行。

    查看 qglobal.h 中foreach 的定义。看起来您可能需要定义 begin 和 end 方法。

    在我的系统上,它位于$QtInstallDir/src/corelib/global/qglobal.h

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 2021-11-14
      • 2018-06-02
      • 2013-02-17
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多