0

The answer here does not work for this pattern in C++17:

template <typename Processor>
void Collection::ProcessCollection(Processor & processor) const
{
    for( int idx = -1 ; ++idx < m_LocalLimit ; )
    {
        if ( m_Data[ idx ] )
        {
            processor( m_Data[idx] );
        }
    }

    const int overflowSize = OverflowSize();

    for( int idx = -1 ; ++idx < overflowSize ; )
    {
        processor( (*m_Overflow)[ idx ] );
    }
}

// How to avoid this repetition for non-const version?
template <typename Processor>
void Collection::ProcessCollection(Processor & processor)
{
    for( int idx = -1 ; ++idx < m_LocalLimit ; )
    {
        if ( m_Data[ idx ] )
        {
            processor( m_Data[idx] );
        }
    }

    const int overflowSize = OverflowSize();

    for( int idx = -1 ; ++idx < overflowSize ; )
    {
        processor( (*m_Overflow)[ idx ] );
    }
}

Due to the argument passed to the lambda Processor being const and not matching its signature.

WilliamKF
  • 41,123
  • 68
  • 193
  • 295
  • What exactly is the determining factor as to whether `ProcessCollection` is `const` or non-`const`? That is, who is making that decision? – Nicol Bolas Jun 14 '19 at 18:15
  • @NicolBolas The `ProcessCollection` member functions are private and are called by other member functions, some of which are `const` and others which are not. – WilliamKF Jun 19 '19 at 20:37

1 Answers1

4

You can factor out the function as a static template one and use it inside both. We can use the template to generate both of these functions:

struct Collection {
    // ...

    template<typename Processor>
    void ProcessCollection(Processor& processor) {
        ProcessCollectionImpl(*this, processor);
    }

    template<typename Processor>
    void ProcessCollection(Processor& processor) const {
        ProcessCollectionImpl(*this, processor);
    }

    template<typename T, typename Processor>
    static void ProcessCollectionImpl(T& self, Processor& processor) {
        for( int idx = -1 ; ++idx < self.m_LocalLimit ; )
        {
            if ( self.m_Data[ idx ] )
            {
                processor( self.m_Data[idx] );
            }
        }

        const int overflowSize = self.OverflowSize();

        for( int idx = -1 ; ++idx < overflowSize ; )
        {
            processor( (*self.m_Overflow)[ idx ] );
        }
    }
};

The T& will deduce Collection& or Collection const& depending on the constness of *this

WilliamKF
  • 41,123
  • 68
  • 193
  • 295
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141