Below is a small test case that demonstrates a problem that I am trying to solve using templates in C++:
template<typename T>
void
unused(T const &) {
/* Do nothing. */
}
int main() {
volatile bool x = false;
unused(!x); // type of "!x" is bool
}
As written below, the g++ v3.4.6 compiler complains:
test.cc: In constructor `test::test()':
test.cc:11: error: invalid initialization of reference of type 'const volatile bool&' from expression of type 'volatile bool'
test.cc:3: error: in passing argument 1 of `void unused(const T&) [with T = volatile bool]'
The goal here is to have unused suppress unused variable warnings that occur in optimized code. I have a macro that does an assertion check and in optimized code the assertion goes away, but I want any variables in the assertion's expression to remain referenced so that I don't get unused variable warnings only in optimized code. In the definition for unused() template function, I use a reference so that no copy constructor code gets inadvertently run so that the call to unused can be completely elided by the compiler.
For those interested, the assertion macro looks like this:
#ifdef NDEBUG
# define Assert(expression) unused(expression)
#else // not NDEBUG
# define Assert(expression) \
{ \
bool test = (expression); \
\
if (!test) { \
if (StopHere(__LINE__, __FILE__, __PRETTY_FUNCTION__, \
#expression, false)) { \
throw Exit(-1); /* So that destructors are run. */ \
} \
} \
}
#endif // else not NDEBUG
For the above test case, I can make the error go away by adding another similar unused function like this:
template<typename T>
void
unused(T const) {
/* Do nothing. */
}
However, then other cases calling unused() fail due to ambiguity when the argument can be made a reference to with something like:
file.h:176: error: call of overloaded `unused(bool)' is ambiguous
myAssert.h:27: note: candidates are: void unused(T) [with T = bool]
myAssert.h:34: note: void unused(const T&) [with T = bool]
So my question is, how can I change unused() or overload it so that it meets the following requirements:
Thanks.
-William
A common (and much simpler) way to achieve this is to just cast the result to void
.
(void) x;
where x is some otherwise unreferenced value.
Charles Nicholson suggests doing something like this to mark unused variables for reasons explained in this article:
#define UNSUSED(a) ((void)sizeof(a))
The short version is... sizeof does not evaluate the expression, but compilers still count it as "used" when it's seen in this context.
I believe this satisfies all 4 of your criteria, specifically because sizeof() can take any valid expression, and because the expression will not be evaluated (and thus will not generate any code).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With