什么是升压:: none_t执行什么道理呢? [英] What is the rationale for boost::none_t implementation?

查看:225
本文介绍了什么是升压:: none_t执行什么道理呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Boost.Optional 使用一个虚拟的类型,以便构建的boost ::可选&LT的未初始化实例; T> 。这种类型被称为 none_t ,和实例已经在方便头文件中定义,让我们写code如以下内容:

 的boost ::可选< INT>未初始化(升压::无);

看着 none_t 的定义,我注意到,它实际上相当于一个指针到成员一些虚拟结构的typedef:

 名字空间boost {命名空间细节{结构none_helper {}; }的typedef INT细节:: none_helper :: * none_t;none_t常量无=(的static_cast&所述; none_t>(0));} //命名空间提升

什么是使用这样一个令人费解的typedef在这样一个简单的空结构?

的优势

 名字空间boost {结构none_t {};none_t常量无;} //命名空间提升


解决方案

嗯,我从来没有想到越挖越深。

一(或多或少明显)的优势,普通的结构,就是现在计算结果为在布尔上下文中。

在另一个计算结果为假的一个好处是,指针构件$ P $有害提升到整型pvented。

所以,我想,它提供了具有计算结果为对象的安全和简洁的方式

编辑:每个人都应该认识到这里(呜呜......)的安全布尔成语的结构

Boost.Optional uses a dummy type to allow constructing uninitialized instances of boost::optional<T>. This type is called none_t, and an instance none is already defined in a header for convenience, allowing us to write code such as the following:

boost::optional<int> uninitialized(boost::none);

Looking at the definition of none_t, I noticed that it is in fact a typedef corresponding to a pointer-to-member to some dummy struct:

namespace boost {

namespace detail { struct none_helper{}; }

typedef int detail::none_helper::*none_t ;

none_t const none = (static_cast<none_t>(0)) ;

} // namespace boost

What are the advantages of using such a convoluted typedef over a simple empty struct like this?

namespace boost {

struct none_t {};

none_t const none;

} // namespace boost

解决方案

Ah, I had never thought to dig deeper.

One (more or less obvious) advantage to a regular struct, is that now none evaluates to false in boolean contexts.

One advantage over another "evaluates to false" is that pointer to member are prevented from harmful promotion to integral types.

So, I guess that it offers a safe and concise way of having a object that evaluates to false.

EDIT: One should recognize here (hum...) the structure of the Safe Bool Idiom.

这篇关于什么是升压:: none_t执行什么道理呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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