// Variant data type
//
// Simplified code as example for the variant data type.
//
// by feyd//godX.de
#include <vector>
#include <string>
#include <stdio.h>
#include <cstdlib>
// Base class ... this is possible with variadic templates also if different variant types are needed
class CVariant
{
public:
enum {
TYPE_NONE = 0,
TYPE_INTEGER = 1,
TYPE_STRING = 2
};
CVariant() :
m_nType(TYPE_NONE), m_nInteger(0) {}
CVariant(int nInteger) :
m_nType(TYPE_INTEGER), m_nInteger(nInteger) {}
CVariant(const char* pString) :
m_nType(TYPE_STRING), m_nInteger(0), m_sString(pString) {}
CVariant(const std::string& sString) :
m_nType(TYPE_STRING), m_nInteger(0), m_sString(sString) {}
CVariant& operator=(int nInteger)
{
m_nType = TYPE_INTEGER;
m_nInteger = nInteger;
return *this;
}
CVariant& operator=(const char* pString)
{
m_nType = TYPE_STRING;
m_sString = pString;
return *this;
}
CVariant& operator=(const std::string& sString)
{
m_nType = TYPE_STRING;
m_sString = sString;
return *this;
}
operator int()
{
if(m_nType==TYPE_INTEGER) {
return m_nInteger;
} else if(m_nType==TYPE_STRING) {
return atoi(m_sString.c_str());
} else {
return 0;
}
}
operator const std::string&()
{
if(m_nType==TYPE_INTEGER) {
char buffer[64];
sprintf(&buffer[0], "%d", m_nInteger);
m_sString = &buffer[0];
return m_sString;
} else if(m_nType==TYPE_STRING) {
return m_sString;
} else {
m_sString.clear();
return m_sString;
}
}
operator const char*()
{
return ((const std::string&)(*this)).c_str();
}
int GetType() const
{
return m_nType;
}
private:
int m_nType;
int m_nInteger;
std::string m_sString;
};
// Application entry point (from libc)
int main(int argc, const char* argv[])
{
printf("Variant test...\r\n\r\n");
{
std::vector<CVariant> variants;
for(int n=1; n<argc; n++)
variants.push_back(argv[n]);
printf(" %d elements:\r\n", (int)variants.size());
for(size_t n=0; n<variants.size(); n++)
printf(" %d. Integer %d, String %s\r\n", (int)n+1, (int)variants[n], (const char*)variants[n]);
printf("\r\n");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108