为什么'的boost :: any`比`无效*`好? [英] Why is `boost::any` better than `void*`?

查看:135
本文介绍了为什么'的boost :: any`比`无效*`好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么先天的优势做的boost ::任何的boost :: any_cast 提供超过使用无效* 的dynamic_cast

What inherent advantages do boost::any and boost::any_cast offer over using void* and dynamic_cast?

推荐答案

的优点是,的boost ::任何是方式更加类型安全比无效*

The advantage is that boost::any is way more type-safe than void*.

例如

int i = 5;
void* p = &i;
static_cast<double*>(p);  //Compiler doesn't complain. Undefined Behavior.
boost::any a;
a = i;
boost::any_cast<double>(a); //throws, which is good

至于你的评论,你不能的dynamic_cast 无效* 。您可以的dynamic_cast 仅从指针和引用其中至少有一个虚函数类类型(又名多态类型)

As to your comment, you cannot dynamic_cast from a void*. You can dynamic_cast only from pointers and references to class types which have at least one virtual function (aka polymorphic types)

这篇关于为什么'的boost :: any`比`无效*`好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆