“ static_cast< void>”的用法是什么?在宏? [英] what is the use of "static_cast<void>" in macro?

查看:88
本文介绍了“ static_cast< void>”的用法是什么?在宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这样的宏定义:

I'm seeing a macro definition like this:

#define ASSERT_VALID_PARAM(param, assertion) {  static_cast<void>(param); if (!(assertion)) { throw InvalidParamError(#param, #assertion, __FILE__, __PRETTY_FUNCTION__, __LINE__); } }

我不知道是否需要 static_cast< void>(参数)在这里。
关于为什么需要这样做的任何想法?

I'm not able to figure out the need of static_cast<void>(param) here. Any idea on why this is needed?

推荐答案

此宏旨在验证某个 real 参数传递特定的验证规则。宏的逻辑部分由两部分组成:

This macro is designed to validate a certain real parameter passes a certain validation rule(s). The logic part of the macro is composed of 2 parts:


  1. 验证 param 是具有有效名称的实参。这是通过使用 static_cast 完成的,如果使用了非法名称,则会生成编译时错误。

  2. 验证断言的真实性。

  1. Validate that param is a real parameter, with a valid name. This is done by using the static_cast, and if an illegal name is used, a compile time error will be generated.
  2. Validate the "truthyness" of assertion. This is done with a simple negating if statement.

如果参数是有效名称,并且断言失败( assertion == false ),使用传入的参数作为字符串(使用 InvalidParamError //msdn.microsoft.com/zh-cn/library/7e3a913x.aspx rel = nofollow> 字符串化运算符# )来初始化错误对象。

If the param is a valid name, and the assertion fails (assertion == false), an InvalidParamError is thrown, using the passed in parameters as strings (using the Stringizing operator #) to initialize the error object.

由于宏中 param 参数的实际用法仅是字符串,因此必须使用实际代码进行验证。由于不需要实际操作,因此使用static_cast,它会丢弃结果,并且有可能进行优化。如果没有该检查,则可以传递任何值,该值将使断言中的信息毫无意义。

Since the actual usage of the param parameter in the macro is only as a string, it has to be validated using actual code. Since no real operation is needed the static_cast is used, which discards the result and can potentially be optimized out. Without that check, you could pass any value which would make the information in the assertion meaningless.

这篇关于“ static_cast&lt; void&gt;”的用法是什么?在宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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