浅析C++中boost.variant的几种访问方法
2019/7/10 22:54:08
本文主要是介绍浅析C++中boost.variant的几种访问方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Boost.Variant
Variant库包含一个不同于union的泛型类,用于在存储和操作来自于不同类型的对象。这个库的一个特点是支持类型安全的访问,减少了不同数据类型的类型转换代码的共同问题。
Variant 库如何改进你的程序?
•对用户指定的多种类型的进行类型安全的存储和取回
•在标准库容器中存储不同类型的方法
•变量访问的编译期检查
•高效的、基于栈的变量存储
Variant 库关注的是对一组限定类型的类型安全存储及取回,即非无类的联合。Boost.Variant
库与 Boost.Any
有许多共同之外,但在功能上也有不同的考虑。在每天的编程中通常都会需要用到非无类的联合(不同的类型)。保持类型安全的一个典型方法是使用抽象基类,但这不总是可以做到的;即使可以做得,堆分配和虚拟函数的代价也可能太高。你也可以尝试用不安全的无类类型,如 void* (它会导致不幸),或者是类型安全得无限制的可变类型,如 Boost.Any
. 这里我们将看到 Boost.Variant
,它支持限定的可变类型,即元素来自于一组支持的类型。
下面将浅谈variant的几种访问方法,一起来学习学习吧。
使用boost::get
boost::variant<int, std::string> v; v = "Hello world"; std::cout << boost::get<std::string>(v) << std::endl;
使用boost::get
来访问,需要给出原始类型,并且这样做不安全,若类型错误,程序将会抛出异常。
使用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; }
使用该模式,需要定义一个类并继承于boost::static_visitor
,在类里面需要重载()操作符,通过boost::apply_visitor
来访问原始类型的值,这样做还是有些繁琐,每增加一个类型,都需要在var_visitor里面增加一个函数,但比使用RTTI里面的修改if-else结构好得多,因为使用访问者模式至少是遵循开放-封闭原则的,即对写开放,对修改封闭。
使用模板函数
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, std::string> v; v = "Hello world"; boost::apply_visitor(var_visitor(), v); return 0; }
将operator()
改成了模板函数的好处就是不用关心variant支持多少类型。
总结
以上就是这篇文章的全部内容,希望本文的内容对大家学习或者使用C++能有所帮助,如果有疑问大家可以留言交流。谢谢大家对找一找教程网的支持。
这篇关于浅析C++中boost.variant的几种访问方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding
- 2024-06-23AI大模型企业应用实战(15)-langchain核心组件
- 2024-06-23AI大模型企业应用实战(16)-langchain核心组件
- 2024-06-23AI 大模型企业应用实战(06)-初识LangChain
- 2024-06-19EntBot.ai: AI Website Chatbot for Product Guides and Development Doc
- 2024-06-17zero-shot-learning-definition-examples-comparison
- 2024-06-06Package Easy(基于 NSIS 的打包exe安装包工具)使用方法-icode9专业技术文章分享
- 2024-06-06基于 casdoor 的 ELK 开源登录认证解决方案: elk-auth-casdoor-icode9专业技术文章分享
- 2024-05-29Elasticsearch慢查询日志配置