浅析C++中boost.variant的几种访问方法
Boost.Variant Variant库包含一个不同于union的泛型类,用于在存储和操作来自于不同类型的对象。这个库的一个特点是支持类型安全的访问,减少了不同数据类型的类型转换代码的共同问题。 Variant 库如何改进你的程序? •对用户指定的多种类型的进行类型安全的存储和取回 •在标准库容器中存储不同类型的方法 •变量访问的编译期检查 •高效的、基于栈的变量存储 Variant 库关注的是对一组限定类型的类型安全存储及取回,即非无类的联合。 下面将浅谈variant的几种访问方法,一起来学习学习吧。 使用boost::get boost::variant<int,std::string> v; v = "Hello world"; std::cout << boost::get<std::string>(v) << std::endl; 使用 使用RTTI void var_print(boost::variant<int,std::string>& v) { if (v.type() == typeid(int)) { std::cout << get<int>(v) << std::endl; } else if (v.type() == typeid(std::string)) { std::cout << get<std::string>(v) << std::endl; } // Else do nothing } int main() { boost::variant<int,std::string> v; v = "Hello world"; var_print(v); return 0; } 使用RTTI技术可以避免类型访问错误而程序异常的情况,但是这样做有点不优雅,每增加一个类型,都需要修改if-else结构,并且使用RTTI会对程序性能有一定影响。 使用访问者模式 class var_visitor : public boost::static_visitor<void> { public: void operator()(int& i) const { std::cout << i << std::endl; } void operator()(std::string& str) const { std::cout << str << std::endl; } }; int main() { boost::variant<int,std::string> v; v = "Hello world"; boost::apply_visitor(var_visitor(),v); return 0; } 使用该模式,需要定义一个类并继承于 使用模板函数 class var_visitor : public boost::static_visitor<void> { public: template<typename T> void operator()(T& i) const { std::cout << i << std::endl; } }; int main() { boost::variant<int,v); return 0; } 将 总结 以上就是这篇文章的全部内容,希望本文的内容对大家学习或者使用C++能有所帮助,如果有疑问大家可以留言交流。谢谢大家对编程小技巧的支持。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |