/*
** Variant and any demostration
** with common type and user-defined type
*/
// Comment the following line if not using STLport
#define _STLP_USE_BOOST_SUPPORT 1
#include <string>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/variant.hpp>
#include <boost/any.hpp>
using std::vector;
using std::string;
using std::endl;
using std::ostream;
using std::for_each;
using boost::variant;
using boost::any;
class PersonalInfo;
typedef any Any;
typedef variant <int, double, string, PersonalInfo> Variant;
typedef vector <Variant> VariantContainer;
typedef vector <any> StoreAnythingContainer;
/* User-defined type */
class PersonalInfo {
public:
PersonalInfo (const string & name, uint16_t age)
{
name_ = name;
age_ = age;
}
~PersonalInfo ()
{
name_.erase ();
age_ = 0;
}
public:
friend ostream & operator<< (ostream & os, const PersonalInfo & pi)
{
os << "Full Name:" << pi.name_ << endl;
os << "Age:" << pi.age_ << endl;
return os;
}
private:
string name_;
uint16_t age_;
};
class PrintContentVisitor: public boost::static_visitor <void> {
public:
void operator () (const string & value) const
{
}
void operator () (int & value) const
{
}
void operator () (double & value) const
{
}
void operator () (const PersonalInfo & value) const
{
}
};
int main(int argc, char *argv[])
{
VariantContainer array;
PrintContentVisitor printer;
array.push_back ("Hello World");
array.push_back (1024);
array.push_back (10.24);
array.push_back (PersonalInfo ("J.Smith", 20));
for_each (
array.begin (),
array.end (),
boost::apply_visitor (printer)
);
system("PAUSE");
return EXIT_SUCCESS;
}