【C++编程】boost::variant
boost::variant
#include <boost/variant.hpp>
#include <string>
#include <iostream>
int main()
{
boost::variant<double, char, std::string> v;
v = 3.14;
std::cout << v << std::endl;
v = 'A';
std::cout << v << std::endl;
v = "Hello, world!";
std::cout << v << std::endl;
}
1. 实例
#include <boost/variant.hpp>
#include <boost/any.hpp>
#include <vector>
#include <string>
#include <iostream>
std::vector<boost::any> vector;
struct output : public boost::static_visitor<>
{
void operator()(double &d) const
{
vector.push_back(d);
std::cout << "double: " << d << std::endl;
}
void operator()(char &c) const
{
vector.push_back(c);
std::cout << "char: " << c << std::endl;
}
void operator()(std::string &s) const
{
vector.push_back(s);
std::cout << "string: " << s << std::endl;
}
};
int main()
{
boost::variant<double, char, std::string> v;
v = 3.14;
boost::apply_visitor(output(), v);
v = 'A';
boost::apply_visitor(output(), v);
v = "Hello, world!";
boost::apply_visitor(output(), v);
}
输出:
[root@node01 demo]# g++ -std=c++11 -lboost_system -lpthread -I/usr/local/include/boost -L/usr/local/lib demo.cc -o demo
[root@node01 demo]# ./demo
double: 3.14
char: A
string: Hello, world!