Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selectively suppress "unused variable" warnings for unused lambdas

Is there any way to suppress "unused variable" warnings for a specific file, namespace, or specific variable?

I ask because I have a namespace containing a big list of lambda functions. Some are not used now, but might be used in time. If these were regular free functions, I would not be warned if some were unused. However, because they are lambdas, I end up with a stack of compiler warnings.

I do not want to use a compiler flag to remove all of this type of warning, as normally, it is very useful to have the compiler catch unused variables. However, a stack of warnings about unused utility functions adds noise to otherwise useful information.

like image 660
learnvst Avatar asked Dec 19 '22 21:12

learnvst


2 Answers

There are two approaches that come to mind. First of all, most build environments enable per-source compiler flags, so you should be able to turn off that warning just for the single file where all those lambdas are defined.

Then there is a general approach to silence such warnings for single variables: use it, but not really do anything with it. On some compilers this can be achieved with a simple cast to void:

auto x = /* ... */;
(void) x;

But more effective is defining a simple function that makes it look (for the compiler) as if the variable was used:

template <class T>
void ignore_unused(T&) {} 

//later...
auto x = /* ... */;
ignore_unused(x);

Note the parameter has no name, so the compiler will not complain about that one to be unused.

The idea is pretty common: do something with the variable that effectively makes no operation but silences the static analyzer that emits the "unused variable" warning.

Boost has a similar function, boost::ignore_unused_variable_warning()

For more information, see Herb Sutter's blog.

like image 124
Arne Mertz Avatar answered Feb 15 '23 23:02

Arne Mertz


In C++ you can static_cast anything to void.

What is the use of such a cast if it does not produce any side effects or a value one might ask?

Precisely to tell the compiler that an object is "used" in a portable way.

So,

auto x =  /*...*/;
static_cast<void>(x);
like image 20
Maxim Egorushkin Avatar answered Feb 16 '23 01:02

Maxim Egorushkin