本文介绍了c ++抽象基类后缀操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于实现共享迭代器接口的问题。

I have a question about implementing a shared iterator interface.

作为postix操作符的常见做法,函数可能如下所示:

As common practice for postix operator the function might look like this:

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

  //increment stuff

  return temp
}


b $ b

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

And most of the time this is fine. In my case I am trying to implement 3 iterators for one class. 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:

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

这种方法称为静态多态性, )完全避开 virtual ,因此使您的对象变小。您可以从基类中省略加载声明,并调用 T :: load static_cast< ; T&>(* this).load()

This approach is called static polymorphism, and allows you (in some cases) to completely eschew virtual and therefore make your objects smaller. You can omit the load declaration from the base classes and call T::load as static_cast<T&>(*this).load().

这篇关于c ++抽象基类后缀操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 08:20