Generic Data Members

Hi,

I'm interested in designing a class for flexible storage of any imaginable type of data in the same member of the class. At first I thought maybe a template would help me, and it would help half way. However it would only help me write any one of these potential types at a time. I couldn't then use the same variable to store another type later. In other words if I had a template with T=int, then it couldn't be used in the same code where it is T=SomeClass. The only thing I can think of is void*. Is that my best bet? Or am I overlooking something? Sorry if this seems like a perl or objective C question, but I'm interested in doing this type of thing within C++, not on the computational end, but on the user interface end.

Thanks,

Sean
The boost::variant type might be useful for this:

http://www.boost.org/doc/libs/1_55_0/doc/html/variant.html
boost::any

edit: its actually very easy to build your own generic type based on boost::any. ive done it before
Last edited on
Works like a charm!
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
#include <cstdlib>
#include <boost/any.hpp>
#include<iostream>
#include<vector>
using namespace std;
class C_StoreAnything
{
public:
    template <class T>C_StoreAnything(T &storeMe)
    :
    dataToStore(&storeMe)
    {

    }
    template <class T>void setValue(T &storeMe)
    {
        dataToStore=&storeMe;
    }
    void printDataAsString()
    {
        cerr<<"data = "<<*boost::any_cast<string*>(dataToStore)<<endl;
    }
    void printDataAsDouble()
    {
        cerr<<"data = "<<*boost::any_cast<double*>(dataToStore)<<endl;
    }
private:
    boost::any dataToStore;
};
int main(int argc,char** argv)
{
    double value1=1.11;
    string value2="2.22";
    C_StoreAnything doubleVal(value1);
    C_StoreAnything stringVal(value2);
    doubleVal.printDataAsDouble();
    stringVal.printDataAsString();
    doubleVal.setValue(value2);
    stringVal.setValue(value1);
    doubleVal.printDataAsString();
    stringVal.printDataAsDouble();
    return 0;
}

data = 1.11
data = 2.22
data = 2.22
data = 1.11
Last edited on
What sort of exception was thrown?
Topic archived. No new replies allowed.