c++ abstract base class postfix operator

前端 未结 1 2023
我在风中等你
我在风中等你 2021-01-18 12:01

I have a question about implementing a shared iterator interface.

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

Iterator         


        
相关标签:
1条回答
  • 2021-01-18 12:42

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

    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().

    0 讨论(0)
提交回复
热议问题