简体   繁体   English

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

[英]c++ abstract base class postfix operator

I have a question about implementing a shared iterator interface. 我对实现共享的迭代器接口有疑问。

As common practice for postix operator the function might look like this: 作为postix运算符的常用做法,该函数可能如下所示:

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

  //increment stuff

  return temp
}

And most of the time this is fine. 多数情况下,这很好。 In my case I am trying to implement 3 iterators for one class. 就我而言,我试图为一个类实现3个迭代器。 Each iterator will load a local collection class with data but each derived iterator would load it in a different way. 每个迭代器将使用数据加载本地集合类,但是每个派生的迭代器将以不同方式加载它。 Because the collection class would be the same and all of the code for the operators( postfix/prefix ++/--, *) would be the same I thought a nice way to implement this would be inheritance: 因为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 }
}

The problem are the postfix operators... They are trying to create an object of an abstract type and then returning it. 问题是后缀运算符...他们正在尝试创建抽象类型的对象,然后将其返回。 Any suggestions for workarounds or structure changes? 有任何解决方法或结构更改的建议吗?

Use the CRTP idiom to make the base class aware of the final class. 使用CRTP习惯用法使基类知道最终的类。 For example: 例如:

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

This approach is called static polymorphism , and allows you (in some cases) to completely eschew virtual and therefore make your objects smaller. 这种方法称为静态多态性 ,它使您(在某些情况下)可以完全避开virtual ,从而使对象更小。 You can omit the load declaration from the base classes and call T::load as static_cast<T&>(*this).load() . 您可以从基类中省略load声明,并以static_cast<T&>(*this).load()调用T::load

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM