'Is this a good way to use static_cast<void>(0) for nothing?
Imagine that we do not have the [[maybe_unused]] attribute in C++.
How we could use this ability before inventing this attribute (I mean, before C++17)?
I found one solution:
static_cast<void>(0)
But I'm not sure that is correct! Can you explain a better solution (doesn't show compiler warnings, and passes static code analyzer)?
Edit: I wrote just one example of casting to void (maybe_unused was one , and below is another and etc ...) :
obj.enabled() ? static_cast<void>(0) : obj.DoThat(); /*as title said doing nothing*/
so I mean static_cast(variable) too.
Solution 1:[1]
static_cast<void>(0)But I'm not sure that is correct!
static_cast<void>(0) doesn't make much sense, but I presume you mean static_cast<void>(maybe_unused_variable);
It is correct in the sense that it is well-formed. The standard doesn't specify when a compiler will warn about unused variables (except for recommending that [[maybe_unused]] suppresses such warning), but a cast to void is a de-facto convention to signify potentially unused names.
Can you explain a better solution
As suggested by Human-Compiler and originally by Herb Sutter, you could call an empty function template:
template <typename T>
void unused(const T&){}
// usage
unused(maybe_unused_variable);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
