首页 / C++ / C++ boost::variant
C++ boost::variant
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++ boost::variant,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2358字,纯文字阅读大概需要4分钟。
内容图文
![C++ boost::variant](/upload/InfoBanner/zyjiaocheng/627/4aa4ef488d2e4b52b85115bc6a29e9f7.jpg)
今天看代码时候发现用了variant,第一次接触这个类,没想到C++还有这种类,
前言
variant类型在C++14并没有加入,在cppreference网站上可以看到该类型将会在C++17加入,若想在不支持C++17的编译器上使用variant类型,我们可以通过boost的variant类型,variant类型可以表示任意一种类型和any类型有些相似,但还是有些区别,比如说variant支持的类型需提前定义,而any类型不需要,获取any类型的值需要给出原始类型,然而variant类型支持多种方式访问,其中一种就是通过访问者模式来访问,是不需要给出原始类型的,下面将浅谈variant的几种访问方式(个人博客也发表了《浅谈boost.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 << boost::get<int>(v) << std::endl;
}
else if (v.type() == typeid(std::string))
{
std::cout << boost::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支持多少类型。
参考资料
转自:https://www.cnblogs.com/highway-9/p/6002306.html
内容总结
以上是互联网集市为您收集整理的C++ boost::variant全部内容,希望文章能够帮你解决C++ boost::variant所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。