C ++为给定列表中的每种类型执行操作 [英] C++ execute an action for each type in a given list
问题描述
我被赋予重构旧代码的费用,偶然发现了这种情况:
I have been given the charge to refactor old code and have stumbled upon this case:
void myClass::doStuff()
{
for( myIterator< Type1 > it( this->getDatabase() ); it; ++it )
{
do1( *it );
do2( *it );
do3( *it );
}
for( myIterator< Type2 > it( this->getDatabase() ); it; ++it )
{
do1( *it );
do2( *it );
do3( *it );
}
for( myIterator< Type3 > it( this->getDatabase() ); it; ++it )
{
do1( *it );
do2( *it );
do3( *it );
}
}
这显然很糟糕,因为我复制了基本相同的代码3因此,我决定使用这样的模板来重构它:
It's obviously bad since I copy basically the same code 3 times so I decided to refactor it using templates like this :
template<class _type> void myClass::do123()
{
for( myIterator< _type > it( this->getDatabase() ); it; ++it )
{
do1( *it );
do2( *it );
do3( *it );
}
}
void myClass::doStuffBetter()
{
do123<Type1>();
do123<Type2>();
do123<Type3>();
}
是否存在其他更容易/更有效的方法来在代码中分解这种重复?
Is there other easier/more productive ways to factorize this kind of repetition in code ?
奖金问题:如果我的类型不是静态的,但在可变参数模板中给出,我将如何做类似的处理?
Bonus question : if my types were not static but given in a variadic template how would I do a similar treatment ?
推荐答案
我发现您的解决方案足够好。
I find your solution good enough.
只是为了好玩,我建议使用以下 doStuffBetter()
Just for fun, I propose the following doStuffBetter()
template <typename ... Types>
void myClass::doStuffBetter()
{
int unused[] { (do123<Types>(), 0)... };
(void)unused; // to avoid a warning
}
应该与C ++ 11一起工作,我想也可以回答您的奖金问题。
Should work with C++11 and I suppose that can respond to your bonus question too.
这篇关于C ++为给定列表中的每种类型执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!