#define _SCL_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include <boost/variant.hpp>
#include <boost/variant/apply_visitor.hpp>//apply_visitor
#include <boost/variant/detail/apply_visitor_delayed.hpp>//apply_visitor_delayed_t
#include <algorithm>
#include <vector>
using namespace boost;
struct var_print : public static_visitor<>
{
template<typename T>
void operator()(T &i) const// 普通类型
{
cout << i << endl;
}
template<typename T>
void operator()(vector<T>& v)
{
for (auto it : v)
{
cout << it << endl;
}
}
};
int main(int argc, char *argv[])
{
boost::variant <int, std::string, double, char> u;// 可单次存放<>中的某一类型
u = 4;
assert(u.type() == typeid(int));
int i = boost::get<int >(u);
std::cout << "int : " << i << std::endl;// int : 4
boost::get<int >(u) *= 10;
std::cout << boost::get<int >(u) << std::endl;// 40
u = "hello world!";
std::string s = boost::get <std::string>(u);
std::cout << "string : " << s << std::endl;// string : hello world!
cout << u.which() << endl;// 1 当前类型的位置
u = 1.2;
double d = boost::get<double >(u);
std::cout << "double : " << d << std::endl;// double : 1.2
u = 'c';
char e = boost::get<char >(u);
std::cout << "char : " << e << std::endl;// char : c
//u = 1.4;
//float f = boost::get<float >(u);// 错误,没有float存储类型
//std::cout << "float : " << f << std::endl;
// 访问者模式
var_print vp;
// 应用访问器需要函数apply_visitor
apply_visitor(vp, u);// c
// 以下两行和apply_visitor(vp, u);效果一样
apply_visitor_delayed_t<var_print> avdt = apply_visitor(vp);
avdt(u);// c
// 针对vector重载operator()访问器
boost::variant <std::string, vector<int>> v;
v = vector<int>({ 1, 2, 3, 4 });
apply_visitor(vp, v);// 1, 2, 3, 4
// 对容器内所有的variant元素进行访问器操作
vector<boost::variant <std::string, vector<int>>> vec;
vec.push_back((v));
for_each(vec.begin(), vec.end(), apply_visitor(vp));// 1, 2, 3, 4
return 0;
}