[英]what is the use of “static_cast<void>” in macro?
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__); } }
I'm not able to figure out the need of static_cast<void>(param)
here. 我无法在这里找出对static_cast<void>(param)
。 Any idea on why this is needed? 对为什么需要这样做有任何想法吗?
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: 宏的逻辑部分由2部分组成:
param
is a real parameter, with a valid name. 验证param
是带有有效名称的真实参数。 This is done by using the static_cast
, and if an illegal name is used, a compile time error will be generated. 这可以通过使用static_cast
,如果使用了非法名称,则会生成编译时错误。 assertion
. 验证assertion
的“真实性”。 This is done with a simple negating if statement. 这是通过简单的否定if语句完成的。 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. 如果参数是有效名称,并且断言失败( assertion == false
),则使用传入的参数作为字符串(使用Stringizing运算符# )来初始化InvalidParamError
,以初始化错误对象。
Since the actual usage of the param
parameter in the macro is only as a string, it has to be validated using actual code. 由于宏中param
参数的实际用法仅是字符串,因此必须使用实际代码进行验证。 Since no real operation is needed the static_cast is used, which discards the result and can potentially be optimized out. 由于不需要实际操作,因此使用static_cast,它会丢弃结果,并且有可能进行优化。 Without that check, you could pass any value which would make the information in the assertion meaningless. 如果没有该检查,则可以传递任何值,该值将使断言中的信息毫无意义。
it is the 'c++ way' of writing 这是“ C ++”的写作方式
(void)param;
it makes 'use' of the variable and thus disables the compiler warning for unused variable 它使变量“使用”,从而禁用未使用变量的编译器警告
static_cast<void>(param);
will evaluate the param
and discard the result. 将评估param
并丢弃结果。
If you don't add the cast to void
: 如果您不将演员表添加到void
:
From cppreference 来自cppreference
4) If new_type is the type void (possibly cv-qualified), static_cast discards the value of expression after evaluating it. 4)如果new_type是void类型(可能是cv限定),则static_cast在对表达式的值求值后将其丢弃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.