I am in the process of creating a generic data class, to help me simplify the parsing of object attributes from text/xml documents. This class will be string based and I will need to be able to cast it to/from pretty much any basic type i.e. char *, bool, int and float. Here's a rough first pass:
class CGeneric
{
public:
CGeneric(const char *pString)
{
strncpy(m_string, pString, sizeof(m_string) - 1);
}
operator const char * () const
{
return((const char *)m_string);
}
operator int () const
{
return((int)atoi(m_string));
}
operator float () const
{
return((float)atof(m_string));
}
void operator = (const char *pString)
{
strncpy(m_string, pString, sizeof(m_string) - 1);
}
void operator = (int value)
{
sprintf(m_string, "%d", value);
}
void operator = (float value)
{
sprintf(m_string, "%f", value);
}
private:
char m_string[32];
};
void TestFunction()
{
CGeneric genericData("12.4");
int myInt = genericData; // myInt = 12
float myFloat = genericData; // myFloat = 12.4
}
This works pretty nicely, but I would really like to add array/random access functionality, which would work something like this:
struct CVector3
{
float x, y, z;
};
void TestFunction()
{
CGeneric genericData("10, 15, -12");
CVector3 pos;
pos.x = genericData<float>[0];
pos.y = genericData<float>[1];
pos.z = genericData<float>[2];
}
Unfortunately I'm having trouble implementing the operator. It isn't possible to create separate functions for each type (I get a compile error because the functions differ only by return type), so the only other way I can see to do this is to declare a template function like this:
template <typename TYPE> TYPE operator [] (int i)
{
return((TYPE)0); // Worry about implementation details later.
}
This compiles, but I do not know how I can then tell the compiler what type I want to access. I tried genericData<int>[0], <int>genericData[0] and genericData[0]<int>, but all produced compile errors. Have I hit a dead end or is there a way to specify the type? If I have hit a dead end, does anyone have any suggestions? Thanks in advance.