如何避免使用 lambda 进行代码重复的常量和非常量集合处理



这里的答案不适用于 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 ] );
    }
}

由于传递给 lambda 的参数Processor是常量并且与其签名不匹配。

您可以将该函数分解为静态模板,并在两者中使用它。我们可以使用模板来生成这两个函数:

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

T&将根据*this的恒常性推断出Collection&Collection const&

最新更新