如何最好地将 VARIANT_BOOL 转换为 C++ bool?

2022-01-14 00:00:00 windows com boolean interop c++

使用 COM 时,布尔值将作为 VARIANT_BOOL 传递,在 wtypes.h 中声明为 short.true 和 false 也有预定义的值:

When using COM boolean values are to be passed as VARIANT_BOOL which is declared in wtypes.h as short. There are also predefined values for true and false:

#define VARIANT_TRUE ((VARIANT_BOOL)-1)
#define VARIANT_FALSE ((VARIANT_BOOL)0)

从 VARIANT_BOOL 转换为 C++ bool 类型的最佳方法是什么?明显的变体是:

Which is the best way to convert from VARIANT_BOOL to C++ bool type? Obvious variants are:

  1. 与 VARIANT_FALSE 比较

  1. compare with VARIANT_FALSE

只需转换为 bool

可以很容易地发明其他方法.

Other ways can be easily invented.

最好的方法是什么 - 最易读、最符合标准、最不容易出现意外错误植入以及最不容易移植到 64 位平台时出现问题?

Which is the best way to do this - most readable, most standart-compliant, least prone to accidential bugs planting and least prone to issues with porting to 64-bit platforms?

推荐答案

比较VARIANT_FALSE.有很多错误代码错误地将 C++ bool true 值(强制转换为整数值 1)传递给期望 VARIANT_BOOL 的函数.如果您与 VARIANT_FALSE 进行比较,您仍然会得到正确的预期值.

Compare to VARIANT_FALSE. There is a lot of buggy code out there that mistakenly passes in the C++ bool true value (cast to the integer value 1) to a function expecting VARIANT_BOOL. If you compare to VARIANT_FALSE, you will still get the correct expected value.

相关文章