cast or convert from a string to an ENUM

 

Is there a way to cast or convert from a string to an ENUM.

This is a simplification of the problem:

enum ENUM_OPS {
   BUY = 1, SELL = 2
};

string sVal = "BUY";

ENUM_OPS eVal;

//eVal = (ENUM_OPS)sVal; //Doesnt works
//eVal = EnumToString(sVal); //Doesnt works

Which is the proper way to assign sVal to eVal?

Thanks!

 
Jose Luis Lominchar:

Is there a way to cast or convert from a string to an ENUM.

This is a simplification of the problem:

Which is the proper way to assign sVal to eVal?

Thanks!

ENUM_OPS eVal = BUY;
 
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   string sVal = "BUY";
   ENUM_OPS eVal;
   Print(EnumToString(eVal=StringToEnum(sVal,eVal)));
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum ENUM_OPS {
   BUY = 1, SELL = 2
};

template<typename T>
T StringToEnum(string str,T enu)
  {
   for(int i=0;i<256;i++)
      if(EnumToString(enu=(T)i)==str)
         return(enu);
//---
   return(-1);
  }
//+------------------------------------------------------------------+
 
Ernst Van Der Merwe:

Thank you very much, it works !

 
Jose Luis Lominchar:

Thank you very much, it works !

You're welcome.

 
Ernst Van Der Merwe:

I had the same issue, your solution helped me too. Thank you.