boost::any 是一个非常灵活的类型安全容器,可以存储任意类型的值,是实现“泛型容器”或“动态类型”的重要工具。
#include <boost/any.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <typeinfo>
// 1. 存储任意类型的值
boost::any a = 42; // int
a = std::string("hello"); // string
a = 3.14; // double
a = true; // bool
// 2. 静态转换(不安全,类型错误时返回 nullptr)
boost::any a = 100;
int* p = boost::any_cast<int>(&a); // 获取指针
if (p) {
std::cout << "Value: " << *p << std::endl;
}
std::string* sp = boost::any_cast<std::string>(&a);
if (!sp) {
std::cout << "不是 string 类型" << std::endl;
}
// 3. 动态转换(类型错误时抛出 boost::bad_any_cast)
try {
int value = boost::any_cast<int>(a); // 成功
std::string s = boost::any_cast<std::string>(a); // 抛出异常
} catch (const boost::bad_any_cast& e) {
std::cout << "类型转换失败: " << e.what() << std::endl;
}
#include <map>
#include <boost/any.hpp>
class Properties {
private:
std::map<std::string, boost::any> data_;
public:
template<typename T>
void set(const std::string& key, const T& value) {
data_[key] = value;
}
template<typename T>
T get(const std::string& key) const {
auto it = data_.find(key);
if (it == data_.end()) {
throw std::runtime_error("Key not found: " + key);
}
return boost::any_cast<T>(it->second);
}
template<typename T>
bool is_type(const std::string& key) const {
auto it = data_.find(key);
if (it == data_.end()) return false;
return it->second.type() == typeid(T);
}
bool has_key(const std::string& key) const {
return data_.find(key) != data_.end();
}
};
// 使用示例
void example_properties() {
Properties props;
props.set("name", std::string("Alice"));
props.set("age", 30);
props.set("salary", 75000.50);
props.set("active", true);
std::cout << "Name: " << props.get<std::string>("name") << std::endl;
std::cout << "Age: " << props.get<int>("age") << std::endl;
std::cout << "Salary: " << props.get<double>("salary") << std::endl;
std::cout << "Has 'email'? " << (props.has_key("email") ? "yes" : "no") << std::endl;
std::cout << "Is 'age' an int? " << (props.is_type<int>("age") ? "yes" : "no") << std::endl;
}