C ++抽象基类后缀运算符

kri*_*ris 4 c++ inheritance operator-overloading operator-keyword

我对实现共享的迭代器接口有疑问。

作为postix运算符的常用做法,该函数可能如下所示:

IteratorClass operator ++(int) {
  IteratorClass temp = *this;

  //increment stuff

  return temp
}
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,这很好。以我为例,我试图为一个类实现3个迭代器。每个迭代器将使用数据加载本地集合类,但是每个派生的迭代器将以不同方式加载它。因为collection类是相同的,并且运算符的所有代码(postfix / prefix ++ /-,*)将是相同的,所以我认为实现此目标的一种好方法是继承:

struct iterator {
  protected:
  Collection collection;
  public:
  operator++(int);
  operator++;
  operator--(int);
  operator--;

  virtual load() = 0;

}

struct iterator1 : public iterator {
  virtual load() { custom load function }
}

struct iterator2 : public iterator {
  virtual load() { custom load function }
}
Run Code Online (Sandbox Code Playgroud)

问题是后缀运算符...他们正在尝试创建抽象类型的对象,然后将其返回。有任何解决方法或结构更改的建议吗?

use*_*342 7

使用CRTP习惯用法使基类了解最终类。例如:

template<typename T>
struct iterator_base {
  public:
  T operator++(int) {
    T temp = static_cast<T&>(*this);
    ++*this;
    return temp;
  }
  T& operator++() {
    // ++ mutation goes here
    return *this;
  }
  // ... likewise for --, etc.
};

struct iterator1: public iterator_base<iterator1> {
  // ... custom load function
};
Run Code Online (Sandbox Code Playgroud)

这种方法称为静态多态性,它使您(在某些情况下)可以完全避开virtual并因此使对象更小。您可以load从基类中省略声明,并调用T::loadstatic_cast<T&>(*this).load()