Selectively suppress unused variable warnings for unused lambda

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

I ask because I have a namespace containing a large list of lambda functions. Some of them are not used right now, but can be used on time. If these were ordinary free functions, I would not have warned if some of them were unused. However, since they are lambdas, I get a stack of compiler warnings.

I want not to use the compiler flag to remove all warnings of this type, as usual, it is very useful that the compiler does not use unused variables. However, a warning stack about unused utility functions adds noise to other useful information.

+4
source share
4 answers

There are two approaches that come to mind. First of all, most building environments allow compiler flags for each source, so you should be able to disable this warning for only one file where all these lambdas are defined.

: , . void:

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

, ( ), :

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

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

, , , .

: - , , , " ".

Boost , boost::ignore_unused_variable_warning()

. Herb Sutter.

+6

++ static_cast - void.

, , ?

, "" .

,

auto x =  /*...*/;
static_cast<void>(x);
+3

Lambdas . - ( operator() ). , () .

block-comment ;). , , .

, , , , , . , (void)var - ( , !). , ( GCC ), __attribute__((unused)) ( [[gnu::unused]] Clang).

.

+2

, . , , . :

auto add_one= [](int x){ return x + 1 } ;

:

std::function<int(int)> gen_addone(void)
{
    static auto l_= [](int x){ return x + 1 ; } ;
    return l_ ;
}   

Sorry, you have to wait until C ++ 1y to automatically return the return type.

+1
source

All Articles