Discussion of article "MQL5 Programming Basics: Lists" - page 6

 
papaklass:

Gentlemen, why don't we try to have a substantive discussion? :)

A correct sheet should not require explicit implementation of a new class to use it for an arbitrary class.

Therefore, the correct implementation should rely on templates.

To be fair, I'm not sure this is realisable at the template level presented.

But that's actually a far cry from the problems in the article.

 
TheXpert:


A correct list should not require explicit implementation of a new class to use it for an arbitrary class...

Do I understand correctly that even if nodes (list elements) have different type and way of connection between them, the list should still have the same implementation, i.e. refer to the same data type? Conditionally CList should include different types of nodes (CSingleNode, CDoubleNode, etc.)...
 
denkir:
Conditionally, CList should include different types of nodes....

Why? ) A container is a set of homogeneous objects.

The difference of the objects themselves can be realised by polymorphism within already objects and has nothing to do with the list.

Когда нужно использовать указатели в MQL5
Когда нужно использовать указатели в MQL5
  • 2010.03.25
  • MetaQuotes Software Corp.
  • www.mql5.com
Все объекты в MQL5 по умолчанию передаются по ссылке, но есть возможность использовать и указатели объектов. При этом есть опасность получить в качестве параметра функции указатель неинициализированного объекта. В этом случае работа программы будет завершена критически с последующей выгрузкой. Автоматически создаваемые объекты как правило такой ошибки не вызывают, и в этом отношении они достаточно безопасны. В этой статье мы попробуем разобраться в чем разница между ссылкой и указателей, когда оправдано использование указателей и как написать безопасный код с использованием указателей.
 
TheXpert:

Why? ) A container is a set of homogeneous objects.

The difference of the objects themselves can be realised by polymorphism within already objects and has nothing to do with the list.

It's clear that a concrete list includes homogeneous nodes. What I meant was that the relationships between the nodes in that list can be different, which requires a different list type for each type of node. If you could create the same list class for nodes of different types, that would be great.... I personally haven't tried it myself yet..... Need to think about higher level of abstraction.....
 
TheXpert:

A correct sheet should not require explicit implementation of a new class in order to use it for an arbitrary class.

Therefore, correct implementation should rely on templates.

To be fair, I'm not sure this is realisable at the template level presented.

But that's actually a far cry from the problems in the article.

As I hate to admit, the expert is right here. Ideally, the leaf class should be implemented on templates. Although the standard CList is implemented on CObject.
 

What TheXpert proposes seems to be clear.

If I understand his idea correctly, all methods of some abstract list should automatically recognise "its" node (this is polymorphism).

In the article, for example, there are user classes CiSingleList (Fig.9), CDoubleList (Fig.11), CiUnrollDoubleList (Fig.12), CiCircleDoubleList (Fig.13).

So, in principle, all of them can be stuffed into one class. But we will have to code each method so that it recognises the type of node it deals with at a particular moment. And this will also require a resource... so not everything is so clear-cut....

Когда нужно использовать указатели в MQL5
Когда нужно использовать указатели в MQL5
  • 2010.03.25
  • MetaQuotes Software Corp.
  • www.mql5.com
Все объекты в MQL5 по умолчанию передаются по ссылке, но есть возможность использовать и указатели объектов. При этом есть опасность получить в качестве параметра функции указатель неинициализированного объекта. В этом случае работа программы будет завершена критически с последующей выгрузкой. Автоматически создаваемые объекты как правило такой ошибки не вызывают, и в этом отношении они достаточно безопасны. В этой статье мы попробуем разобраться в чем разница между ссылкой и указателей, когда оправдано использование указателей и как написать безопасный код с использованием указателей.
 
It's good to see justice prevail at least once in a while. ))
 
denkir:
It is clear that a particular list includes homogeneous nodes. What I meant was that the relationships between the nodes in that list can be different, which requires a different list type for each type of node. If you could create the same list class for nodes of different types, that would be great.... I personally haven't tried it myself yet..... Need to think about the higher level of abstraction.....
You only need one node type. See the implementation of the standard CObject and the implementation of CArray, CList, CTree collections: MQL5 Reference --> Standard Library --> Classes for Data Organisation.
Документация по MQL5: Стандартная библиотека
Документация по MQL5: Стандартная библиотека
  • www.mql5.com
Стандартная библиотека - Документация по MQL5
 
...is a lot of work. Practically, who's gonna show me?
 
denkir:

What TheXpert proposes seems to be clear.

If I understand his idea correctly, all methods of some abstract list should automatically recognise "its" node (this is polymorphism).

In the article, for example, there are user classes CiSingleList (Fig.9), CDoubleList (Fig.11), CiUnrollDoubleList (Fig.12), CiCircleDoubleList (Fig.13).

So, in principle, all of them can be stuffed into one class. But we will have to code each method so that it recognises the type of node it deals with at a particular moment. And this will also require a resource... so not everything is so clear-cut...

What's there to code?

#include <Object.mqh>
#include <Arrays\ArrayObj.mqh>

enum ENUM_CLASS_TYPE
{
   HUMAN,
   ANIMAL,
   CAR
};

class Community : public CObject
{
   public:
      ENUM_CLASS_TYPE TypeCommunity(){return type;}
   protected:
      Community(ENUM_CLASS_TYPE cType)
      {
          type = cType;
      }
      
   private:
      ENUM_CLASS_TYPE type;
};

class Human : public Community
{
   public:
      Human() : Community(HUMAN){;}
      int IQ(){return 90;}
};

class Animal : public Community
{
   public:
      Animal() : Community(ANIMAL){;}
      int CountLegs(){return 4;}
};

class Car : public Community
{
   public:
      Car() : Community(CAR){;}
      int Speed(){return 20;}
};

void OnStart()
{
   CArrayObj elements;
   CObject* object = NULL;
   while(elements.Total() < 100)
   {
      switch(rand()%3)
      {
         
         case HUMAN:
            object = new Human();
            break;
         case ANIMAL:
            object = new Animal();
            break;
         case CAR:
            object = new Car();
            break;
      }
      elements.Add(object);
   }
   while(elements.Total() > 0)
   {
      Community* AnyObject = elements.At(0); 
      switch(AnyObject.TypeCommunity())
      {
         case HUMAN:
         {
            Human* human = AnyObject;
            printf("Element is Human, it's IQ is: " + (string)human.IQ());
            break;
         }
         case ANIMAL:
         {
            Animal* animal = AnyObject;
            printf("Element is anima, it has " + (string)animal.CountLegs() + " legs.");
            break;
         }
         case CAR:
         {
            Car* car = AnyObject;
            printf("Element is car. It has speed " + (string)car.Speed() + " km/h");
            break;
         }
      }
      elements.Delete(0);
   }
}
First grade, second quarter. Unfortunately, you can't do without a Community intermediary, because MQL5 has extremely weak type control. But if we had a ClassToString function like EnumToString() at our disposal, everything could be organised much more elegantly and easily.