Pointers to Functions

To add comments, please log in or register
IN BHM
57
IN BHM  
In C++, you can have a pointer to a funtion, giving the programmer the ability to have arrays of funtions and variable funtions and functions in objects. (here's an example from http://cplusplus.com/doc/tutorial/pointers.html)
// pointer to functions
#include <iostream>
using namespace std;

int addition (int a, int b)
{ return (a+b); }

int subtraction (int a, int b)
{ return (a-b); }

int (*minus)(int,int) = subtraction;

int operation (int x, int y, int (*functocall)(int,int))
{
int g;
g = (*functocall)(x,y);
return (g);
}

int main ()
{
int m,n;
m = operation (7, 5, addition);
n = operation (20, m, minus);
cout <<n;
return 0;
}
How is can this be done in MQL?
Ralph Ronnquist
99
Ralph Ronnquist  
I don't think you can have such beasts in the MQL code, but you would need to enumerate your functions and e.g. use a switch statement to map function number to function call. It might look partly like this:

#define OPaddition 45
#define OPsubtraction 312
int minus = OPsubtraction;

int operation(int x,int y,int op) {
switch ( op ) {
case OPaddition: return addition( x, y );
case OPsubtraction: return subtraction( x, y );
}
return( 3 );
}
IN BHM
57
IN BHM  
Thanks for you help
Tom Sasson
238
Tom Sasson  
IN BHM:
Thanks for you help

This post is old, but since the subject is unanswered and it is relevant even to this day - this is how you use function pointers in MQL4:

// pointer to functions
typedef int(*MyFuncType)(int,int);

int addition (int a, int b)
{ return (a+b); }

int subtraction (int a, int b)
{ return (a-b); }

int operation (int x, int y, MyFuncType myfunc)
{
   int g;
   g = myfunc(x,y);
   return (g);
}

int OnInit()
{
   int m,n;
   m = operation (7, 5, addition);
   n = operation (20, m, minus);
   Print(n);
   return(INIT_FAILED);  //just to close the expert
}
To add comments, please log in or register