1. Boost.Any
boost::any
并不能真的存储任意类型的值; Boost.Any 需要一些特定的前提条件才能工作。 任何想要存储在 boost::any
中的值,都必须是可拷贝构造的。 因此,想要在 boost::any
存储一个字符串类型的值, 就必须要用到 std::string
, 就像在下面那个例子中做的一样。
#include <boost/any.hpp> #include <string> int main() { boost::any a = 1; a = 3.14; a = true; a = std::string("Hello, world!"); }
用 boost::any_cast
来定义一个指向 boost::any
中内容的指针,想要检查 boost::any
是否为空, 你可以使用 empty()
函数。 想要确定其中具体的类型信息, 你可以使用 type()
函数
boost::any a = 1; if (!a.empty()) { int *i = boost::any_cast<int>(&a); std::cout << *i << std::endl; }
2. Boost.Variant
Boost.Variant 只能被视为固定数量的类型, 可以使用独立的 boost::get()
函数获取其中的数据。
#include <boost/variant.hpp> #include <string> std::vector<boost::any> vector; struct output : public boost::static_visitor<> { void operator()(double &d) const { vector.push_back(d); } void operator()(char &c) const { vector.push_back(c); } void operator()(std::string &s) const { vector.push_back(s); } }; int main() { boost::variant<double, char, std::string> v; v = 3.14; v = 'A'; v = "Hello, world!"; std::cout << boost::get<double>(v) << std::endl; std::cout << boost::get<char>(v) << std::endl; std::cout << boost::get<std::string>(v) << std::endl; boost::apply_visitor(output(), v); boost::apply_visitor(output(), v); boost::apply_visitor(output(), v); }