I finally found a good use for function pointers.

To add comments, please log in or register
nicholi shen
nicholi shen  

Here is an example of putting function pointers to good use. Those who know javascript or python will likely recognize this pattern immediately. 

This is a generic object vector that I frequently use, and I've added a filter method which takes a function as an argument and returns a pointer to a new vector. The new vector is added to a "garbage collector" so there is no need for memory management, however, if the scope of the original (non-filtered) collection runs out before the scope of the filtered vector then there will be an error due to the object getting deleted. 


#include <arrays/arrayobj.mqh>

typedef bool (*FilterFunc) (CObject*);

template <typename T>
class objvector : public CArrayObj {
   CArrayObj   m_garbage_collector;
   T operator[](const int index)const{return this.At(index);}
   objvector<T>* filter(FilterFunc func) {
      objvector<T>* new_vector = new objvector<T>();
      int size = this.Total();
      for (int i=0; i<size; i++) 
         if (func(this[i])) 
      return new_vector;

Use example. 

class Trade : public CObject {
   int  ticket;
   double profit;
   Trade(int _ticket) {
      if (OrderSelect(_ticket, SELECT_BY_TICKET)) {
         ticket = _ticket;
         profit = OrderProfit();

bool fWin(CObject *obj) {
   return ((Trade*)obj).profit > 0;

bool fLose(CObject *obj) {
   return ((Trade*)obj).profit < 0;

bool fSymbol(CObject *obj) {
   return (OrderSelect(((Trade*)obj).ticket, SELECT_BY_TICKET)
      && OrderSymbol() == _Symbol);

void OnStart() {
   objvector<Trade*> all, *winners, *losers, *my_symbol_losers;
   for (int i=0; OrderSelect(i, SELECT_BY_POS, MODE_HISTORY); i++)
      all.Add(new Trade(OrderTicket()));
   winners = all.filter(fWin);
   losers = all.filter(fLose);
   my_symbol_losers = losers.filter(fSymbol);
   printf("winners=%d, losers=%d, all=%d", winners.Total(), losers.Total(), all.Total());
To add comments, please log in or register