Let us suppose that we have a function of n variables
y = f (x1, ..., xn)
Such a function I would like to pass as an argument.
In Matlab the following construction using a handle is available:
function y=func(x)
y = sin(x(0)) * cos(x(1)) //Any definition, not important
p_func=@func; //Define handle
It is possible to use the handle as a parameter of another function:
y = function2(p_func, n);
where n represents a dimension…
How to rewrite this code using C++? We use a simple model with the function template
temmplate <typename T>
T func( const T *arg, const short n) {return sin(arg[0]) * cos(arg[1])};
where xi arguments are represented by the 1-dimensional array of n elements. The problem is that in this case it is not possible to use a pointer to the function template
template <class T>
static T ( *pfunc ) ( const T *arg, const short n )
only a specialization… Perhaps another model could be more appropriate…Thanks for your help…
Remark:
I know that a class template is useful
template <typename T>
class Foo
{
T func( const T *args, const short n);
};
and this construction works:
template <class T>
static T ( *pfunc ) ( const T *arg, const short n )
But it may not be used in the current model of the library (I can not affect this).
C++ is a statically typed language. Every object in C++, whether a function pointer, or whatever, must have a specific type. And the type of a function pointer is based on the types of arguments that the function to be pointed to is given.
A template is not an object, so you can’t get a pointer to one. You can get a pointer to an instantiation of a template. Using your
funcdefinition,func<int>is a function that takes aconst int*and ashort. You can get a pointer tofunc<int>. Butfuncis a template; you can’t get a pointer to a template.That’s why C++ programs often throw functors around instead of function pointers. Functors can have a template
operator()method, so you can call them as though you were passing around template functions. But since you say that you have to use a function pointer, there’s not much that can be done.