-
Notifications
You must be signed in to change notification settings - Fork 235
Type validation helpers
The type validation helpers prevent accidental type conversions that would normally be permitted by the language.
The helpers permit a restricted set of types for the parameter, suppressing many categories of error-prone implicit conversions.
These helpers are useful primarily in macros, since macros cannot specify types for their parameters. For example, these helpers are employed extensively in the Error handling helpers to validate the types given to macro parameters.
The type validation helpers are defined in wil/common.h
.
#include <wil/common.h>
template<typename T> constexpr bool verify_bool(const T& val);
Returns val
converted to a bool
. The val
may be one of the following:
bool
BOOL
BOOLEAN
-
boolean
(C++/CX) - A class with an explicit
bool
conversion operator.
Other types are rejected and will generate a compile-time error of the form
Wrong Type: bool/BOOL/BOOLEAN/boolean expected
Examples
#define BEEP_IF(condition) do { if (wil::verify_bool(condition)) { Beep(); } } while ((void)0, 0)
wil::com_ptr<IUnknown> thing;
std::vector<int> vector;
BEEP_IF(thing); // okay, com_ptr has bool conversion operator
BEEP_IF(InSendMessage()); // okay: InSendMessage returns BOOL
BEEP_IF(vector.empty()); // okay: std::vector<T>::empty() returns bool
BEEP_IF(CoRevertToSelf()); // not okay: CoRevertToSelf returns HRESULT, not bool
template<typename T> constexpr BOOL verify_BOOL(const T& val);
Returns val
if it is of type BOOL
. All other types are rejected with a compile-time error of the form
Wrong Type: BOOL expected
Examples
#define BEEP_IF(condition) do { if (wil::verify_BOOL(condition)) { Beep(); } } while ((void)0, 0)
wil::com_ptr<IUnknown> thing;
std::vector<int> vector;
BEEP_IF(thing); // not okay: com_ptr is not a BOOL
BEEP_IF(InSendMessage()); // okay: InSendMessage returns BOOL
BEEP_IF(vector.empty()); // not okay: std::vector<T>::empty() returns bool
BEEP_IF(CoRevertToSelf()); // not okay: CoRevertToSelf returns HRESULT, not bool
template<typename T> constexpr HRESULT verify_hresult(const T& val);
Returns val
if it is of type HRESULT
. All other types are rejected with a compile-time error of the form
Wrong Type: HRESULT expected
Examples
#define BEEP_IF_FAILED(hr) do { if (FAILED(wil::verify_hresult(hr))) { Beep(); } } while ((void)0, 0)
BEEP_IF_FAILED(InSendMessage()); // not okay: InSendMessage returns BOOL
BEEP_IF_FAILED(CoRevertToSelf()); // okay: CoRevertToSelf returns HRESULT