Function with UnKnow Type
Hi to all, I hope uyou can help with the following situation i have:
I have to write a function that receives a parameter, that is unknow until runtime, meaning one of the parameters could be:
CString, int, double, bool or something else
The function receive additional parameters that are know and one that is unknow, for example:
void MyMethod(char *Mychar, int MyInt, <UnKnow Type> MyUnknowType);
Is possible to write this kind of functions?
I try using the Template like
template <class T>
void MyMethod (char *Mychar, int MyInt, T MyUnknowType)
{
Do Something
memberclass = MyInt;
}
The problem is that the function has to use a data member of my class and the (template)method dot reconized that variable member.
And I don't want to rewrite all the class like template only for one function
Thanks
dev.cplusplus
Junior Poster in Training
61 posts since Jun 2006
Reputation Points: 10
Solved Threads: 0
There is no such thing as a CString in c++ me thinks.
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
why don't you initialize your unknown variable as a string, and depending on its value you convert it to int, double, boolean, or leave it as a string... you may use atoi() to compare numbers and strings such as "true" and "false" to compare boolean... if there is a dot in middle of the string and the rest of the characters are numbers, then it is a double... and if not, it is a string...
Nichito
Posting Virtuoso
1,602 posts since Mar 2007
Reputation Points: 424
Solved Threads: 57
you could also make it a structure that contains a union, something like the VARIANT structure that is used frequently by MS-Windows compilers such as VC++ and VB. It looks like this:
typedef enum
{
UNKNOWN = 0,
STRING,
SHORT,
<etc. etc. for each data type
} DATATYPE;
structure Variant
{
DATA_TYPE variable_type;
union
{
unsigned char* strArray;
unsigned short usVal;
short sVal;
int iVal;
unsigned int uiVal;
long lVal;
unsigned long ulVal;
float fVal;
double dVal;
};
};
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343