You don't need to know anything about types if you use typeid:
#include <typeinfo>
#include <iostream>
using namespace std;
struct var_base
{
const type_info & t;
var_base(const type_info & t) : t(t) {};
virtual ~var_base() {};
};
template<class T> struct var : var_base
{
T value;
var(T x) : var_base(typeid(T)), value(x) {};
};
struct variant {
const static int max_size=16;
char data[max_size];
var_base & v;
variant() : v(*(var_base*)data) {
new (data) var<int>(0);
}
const type_info & getType() { return v.t; }
template<class T> T & get() {
assert(getType()==typeid(T));
return static_cast< var<T> &>(v).value;
}
template<class T> void set(const T & value) {
// Compile time assert is also possible here.
assert(sizeof(var<T>)<=max_size);
v.~var_base();
new (data) var<T>(value);
}
};
main()
{
variant v;
v.set<float>(1.2);
cout << v.getType().name() << endl;
cout << v.get<float>();
cout << v.get<int>(); // Assert fails
}
Note that you can get rid of max_size, if you can accept that the value is dynamically allocated. I just wanted to show that in place allocation works too, if you know the size of the largest type.