How to create a function template that treats numeric types differently than all other types?

 

Hello,

The MQL5 Reference has a page on function templates ( https://www.mql5.com/en/docs/basis/oop/templates ) which has the following function template:

template<typename T> 
T ArrayMax(T &arr[]) 
  { 
   uint size=ArraySize(arr); 
   if(size==0) return(0);           
    
   T max=arr[0]; 
   for(uint n=1;n<size;n++) 
      if(max<arr[n]) max=arr[n]; 
//--- 
   return(max); 
  }

I would like to change this function so that it uses the above logic only if the array parameter "T &arr[]" is a numeric array, and does some other logic if "T" is a non-numeric type.

Is the best way to check if "T" is a numeric type by making a function that checks every possible numeric type like this?

template<typename T> 
bool IsNumeric(const T &t) 
  { 
   return(typename(T) == "double" || typename(T) == "int" /* || ...... enter one condition for each numeric type here */ ); 
  }

Is there a more elegant, more performant, or more robust way to check if a templatized type is numeric?

I'm concerned about the fact that typename(T) returns a string, instead of an enum or an integral type to indicate the type of the parameter "T".

Thank you very much in advance,

Robox

Documentation on MQL5: Language Basics / Object-Oriented Programming / Function templates
Documentation on MQL5: Language Basics / Object-Oriented Programming / Function templates
  • www.mql5.com
Language Basics / Object-Oriented Programming / Function templates - Reference on algorithmic/automated trading language for MetaTrader 5
 
Robox: Is there a more elegant, more performant, or more robust way to check if a templatized type is numeric?

You shouldn't care. The function only requires that Datatype T has a copy constructor (T max=...) and a comparison operator (max<arr[n])

Any data type that has those two will work in the template and that includes strings and classes. For strings your function will return the  lexicographical last item - no numeric type needed. See also see Sort multiple arrays - MQL4 and MetaTrader 4 - MQL4 programming forum where I have a second function which i pass a custom comparator for those data types that don't have a comparison operator (or I want a different operation.)

Any that don't will not compile.

 
whroeder1:

You shouldn't care. The function only requires that Datatype T has a copy constructor (T max=...) and a comparison operator (max<arr[n])

Any data type that has those two will work in the template and that includes strings and classes. For strings your function will return the  lexicographical last item - no numeric type needed. See also see Sort multiple arrays - MQL4 and MetaTrader 4 - MQL4 programming forum where I have a second function which i pass a custom comparator for those data types that don't have a comparison operator (or I want a different operation.)

Any that don't will not compile.

Thanks, @whroeder1! I used your advice and everything works perfectly.

I noticed that MQL5 can even handle comparisons of "color" objects with the default comparison operators, unlike C#, which was one of my concerns.

Thanks again.  I always appreciate the quality of your answers.

Robox

 

Since the build 1570 you can overload template functions, that is provide a function with specific typification.

Forum on trading, automated trading systems and testing trading strategies

New MetaTrader 5 Platform Build 1570: Improved Market showcase and extended MQL5 template functions

MetaQuotes Software Corp., 2017.03.22 17:03

New MetaTrader 5 Platform Build 1570: Improved Market showcase and extended MQL5 template functions

MetaTrader 5 platform update is to be released on March 24, 2017. The update will feature the following changes:

  1. Terminal: Updated the showcase of the MetaTrader Market store of applications. Now, you can browse through trading robots and technical indicators more conveniently. We have updated the design and added product selections:

    • The main page now features popular experts, indicators, new Market products, as well as top free applications.
    • The Experts, Indicators and Utilities sections now have subsections: grid and hedging robots, trend and multi-currency indicators, and much more.




  2. Terminal: Fixed the client terminal update and built-in purchases in the Market, Signals and Virtual Hosting when using a Windows account with limited rights.
  3. Terminal: Fixed occasional incorrect sorting of position history.
  4. Terminal: Optimized and fixed display of the Exposure tab.
  5. MQL5: Added support for overloading template functions using parameters. For example, we have a template function that writes the value of the second parameter to the first one using typecasting. MQL5 does not allow typecasting string to bool. However, we can do that ourselves. Let's create an overload of a template function:
    //+------------------------------------------------------------------+
    //| Template function                                                |
    //+------------------------------------------------------------------+
    template<typename T1,typename T2>
    string Assign(T1 &var1,T2 var2)
      {
       var1=(T1)var2;
       return(__FUNCSIG__);
      }
    //+------------------------------------------------------------------+
    //| Special overload for bool+string                                 |
    //+------------------------------------------------------------------+
    string Assign(bool &var1,string var2)
      {
       var1=(StringCompare(var2,"true",false) || StringToInteger(var2)!=0);
       return(__FUNCSIG__);
      }
    //+------------------------------------------------------------------+
    //| Script program start function                                    |
    //+------------------------------------------------------------------+
    void OnStart()
      {
       int i;
       bool b;
       Print(Assign(i,"test"));
       Print(Assign(b,"test"));
      }
    As a result of the code execution, we can see that the Assign() template function has been used for the int+string pair, while the overloaded version has already been used for the bool+string pair during the second call.
    string Assign<int,string>(int&,string)
    string Assign(bool&,string)

  6. MQL5: Added explicit specialization of template functions. To do this, specify typification parameters before the list of the call parameters:
    template<typename T>
    T Func() { return (T)0; }
      
      
    void OnInit()
      {
       Func<double>();   // explicit template function specialization
      }
    Thus, typification is performed by explicit specification of types rather than via the call parameters.

  7. MQL5: Optimized display of custom indicators with the DRAW_ZIGZAG drawing type.
  8. MQL5: Added the new values to the ENUM_DEAL_TYPE deal types enumeration:

    • DEAL_DIVIDEND — dividend operations.
    • DEAL_DIVIDEND_FRANKED — franked (non-taxable) dividend operations (tax is paid by a company, not a client).
    • DEAL_TAX — charging a tax.

  9. MQL5: Fixed display of custom indicators with the DRAW_FILLING drawing type. In case the upper and lower line coordinates coincide, a thin line is drawn.
  10. MQL5: Fixed calculating the Bitmap Label object coordinates when setting the CHART_SHOW parameter to 'false'. The parameter is set by the ChartSetInteger function and allows hiding all price chart elements to create a custom program interface.
  11. MQL5: Fixed re-encoding of 24-bit images when placing them to MQL5 application resources.
  12. MQL5: Fixed printing structures using the ArrayPrint function.
  13. MQL5: Updated the MQL5 standard libraries.
  14. MetaEditor: Added translation of the user interface into Malay.
  15. Signals: Fixed opening a signal page in the terminal when moving from the MQL5.community website while not connected to a trading account.
  16. Tester: Fixed the CopyTicks function operation in the strategy tester.
  17. Tester: Fixed sorting Withdrawal trades when generating a report.
  18. Tester: Fixed modifying pending orders.
  19. Hosting: Fixed display of the virtual hosting wizard on ultra-high resolution screens (4К).
  20. Updated documentation.

The update will be available through the LiveUpdate system.


 
Stanislav Korotky:

Since the build 1570 you can overload template functions, that is provide a function with specific typification.



Thanks, @Stanislav Korotky. It's so great that the MQL team decided to add this C++ feature into the language... not just template functions, but as you mentioned even template specialization.