什么是双重否定的宏定义的目的,就像(!!(表达式))? [英] What is the purpose of a double negative in macro definition, like (!!(expr))?

查看:246
本文介绍了什么是双重否定的宏定义的目的,就像(!!(表达式))?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  双重否定在C ++中code。

我读一个code群,并找到这样的:

I'm reading a code base, and find something like this:

#define uassert(msgid, msg, expr) (void)((!!(expr))||(uasserted(msgid, msg), 0))

我不明白,为什么(!!(表达式))是用来代替单一的(表达式)。无论如何,双重否定表示肯定的,不是吗?我缺少的东西吗?

I cannot figure out why (!!(expr)) is used instead of a single (expr). Anyway, a double negative means positive, is not it? Am I missing something?

推荐答案

有投一个前pression为bool的方法。在C ++虽然,运营商!可以重载。另一种方式为C / C ++:

It is a way to cast an expression to bool. In C++ though, operator! can be overloaded. Another way for C/C++:

0 != (expr)

C ++唯一方法:

C++ only way:

static_cast<bool>(expr)


多想想C ++运算符重载,有意义避免使用运营商。像Boost.Spirit和Boost.Lambda库使用前pression模板和懒惰的评价,使前pressions像(表达式)||电话()可能表现并不如预期。宏观最防弹版本是这样的:

Thinking more about C++ operator overloading, it make sense to avoid using operators. Libraries like Boost.Spirit and Boost.Lambda use expression templates and lazy evaluation, so that expressions like (expr) || call() may behave not as expected. The most bullet proof version of that macro looks like this:

#define uassert(expr) if(expr) {} else { uasserted(...); }

下面,只使用 EXPR 到布尔转换。在所需其他分支从前pressions保护诸如 uassert(十)其他something_else();

Here, only conversion of expr to bool is used. The else branch is needed to protect from expressions like uassert(x) else something_else();.

这篇关于什么是双重否定的宏定义的目的,就像(!!(表达式))?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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