我有两个A和B类。唯一的字段是数组及其大小。所有方法都完全相同,唯一的区别在于对所有方法所采用的索引整数的解释。我想模板化,以便我可以使用std :: plus和另一个使用std :: minus
进行反对一些代码:
class AB {
int dim;
int *tab;
public:
// obvious ctor & dtor
void fun1( int a, int b );
void fun2( int a, int b );
void fun3( int a, int b );
}
void AB::fun1( int a, int b ) {
// operation of "interpretation" here i.e. addition or subtraction of ints into indexing int _num
// some operation on tab[_num]
}
我该怎么做?
答案 0 :(得分:3)
它看起来像这样:
template< typename Op >
void AB::fun1( int a, int b )
{
Op op;
tab[ op( a, b ) ];
};
它将被实例化为:
AB ab;
ab.fun1< std::plus< int > >( 1, 2 );
ab.fun1< std::minus< int > >( 1, 2 );
如果所有方法都出现这种情况,那么模板AB
可能更有意义:
template< typename Op >
class AB
{
... use as above ...
};
这假定操作是无状态的,因此创建此类型的默认构造对象等同于任何其他实例。在这种假设下,代码甚至可以像Op()( a, b )
一样编写。