Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

templating a function in c++

Tags:

c++

templates

I have two classes A and B. The only fields are an array and its size. All of the methods are precisely the same the only difference consisting in the interpretation of the indexing integers taken at all of the methods. I want to template that so that I can istantiate one with std::plus and the other one with std::minus

A bit of code:

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

How can I do that?

like image 891
infoholic_anonymous Avatar asked Dec 06 '25 02:12

infoholic_anonymous


1 Answers

It would look something like this:

template< typename Op >
void AB::fun1( int a, int b )
{
    Op op;

    tab[ op( a, b ) ];
};

and it would be instantiated like this:

AB ab;
ab.fun1< std::plus< int > >( 1, 2 );
ab.fun1< std::minus< int > >( 1, 2 );

If this happens for all of the methods, then it may make more sense to template AB instead:

template< typename Op >
class AB
{
    ... use as above ...
};

This assumes that the operation is stateless, so that creating a default constructed object of such type is equivalent to any other instance. Under this assumption, the code could even be written like this Op()( a, b ).

like image 151
K-ballo Avatar answered Dec 07 '25 18:12

K-ballo