Search code examples
c++templatesgeneric-programmingfunction-object

a call to template-function - is it legal?


I have a template function (generic func to find the minimum), which look's like that:

template<class T, class Func>
int findmin(const T* a, int n, Func less){
   //...
}

and a call:

int smallest_matrix(const Matrix*a, int n){
    return findmin(a,n,less_matrices);
}

where less_marices is:

bool less_matrices(const Matrix& m1, const Matrix& m2){
     //...
}

Is that right syntax?

Shouldn't I define a function-object with operator () which will do the boolean check that less_matrices do, and the call for findmin shouldn't it look like:

 int smallest_matrix(const Matrix*a, int n){
    minMatrixFunc f;
    return findmin<Matrix, minMatrixFunc>(a,n,f);
}

where minMatrixFunc is a function-object with the right operator()???


Solution

  • Is that right syntax?

    Yes.

    Shouldn't I define a function-object with operator ()

    You may, but it's not necessary.

    You don't show the definition of findmin. But presumably, all you do with Func less is use the function call operator on it: less( argument_list ). If so, any callable type will do as long as the overload resolution finds a matching argument list. That includes pointers to functions, which is what you had used.