本文介绍了如何使用Lambda避免代码重复const和非const收集处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不适用于C ++ 17中的该模式:
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 ] );
}
}
由于传递给lambda的参数处理器
为常量且不匹配其签名。
Due to the argument passed to the lambda Processor
being const and not matching its signature.
推荐答案
您可以分解函数作为一个静态模板,并在两个模板中都使用它。我们可以使用模板来生成这两个函数:
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 ] );
}
}
};
T&
将得出 Collection&
或 Collection const&
,具体取决于 * this
The T&
will deduce Collection&
or Collection const&
depending on the constness of *this
这篇关于如何使用Lambda避免代码重复const和非const收集处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!