How to judge variable types ?
I hope to perform different treatment by judging variable types in a function. Does MQL5 can do it?
void Test(double input)
void Test(int input)
void Test(datetime input)
Simply use typename as a function directly:
template<typename T> void Test(T a) { if(typename(T)=="double") { printf("double"); } if(typename(T)=="int") { printf("int"); } }
Sure you can, of course not to build complex generic code, but it's useful.
template<typename Т> uint Write(const Т value,int length=-1) { string typeх = typename(Т); if(typeх=="double") return(FileWriteDouble(handleф,(double)value)); if(typeх=="long" || typeх=="ulong" || typeх=="datetime") return(FileWriteLong(handleф,(long)value)); if(typeх=="float") return(FileWriteFloat(handleф,(float)value)); if(typeх=="string") return(FileWriteString(handleф,(string)value,length)); //--- remains all integer types return(FileWriteInteger(handleф,(int)value,sizeof(Т))); }EDIT: Source code updated to fix the warnings. Thanks to Dominik.
Yes, you're right, my codes only works for basic types.
Your library is too complex to understand for me. I will take time to study it.
Thanks.
Got some inputs from a MQ dev. typename(T) is not a function, so provided we do these changes :
template<typename Т> uint Write(const Т value,int length=-1) { if(typename(Т)=="double") return(FileWriteDouble(handleф,(double)value)); if(typename(Т)=="long" || typename(Т)=="ulong" || typename(Т)=="datetime") return(FileWriteLong(handleф,(long)value)); if(typename(Т)=="float") return(FileWriteFloat(handleф,(float)value)); if(typename(Т)=="string") return(FileWriteString(handleф,(string)value,length)); //--- remains all integer types return(FileWriteInteger(handleф,(int)value,sizeof(Т))); }
The compiler will optimize it. So the above is equivalent to :
template<typename Т> uint Write(const Т value,int length=-1) { return(FileWrite<Т>(handleф,(Т)value)); // Not possible in MQL, just to explain the workaround. }
I hope to perform different treatment by judging variable types in a function. Does MQL5 can do it?