C++ Logo


Advanced search

Allow maybe_unused for lambda captures?

From: Markus Dreseler <isocpp.org_at_[hidden]>
Date: Sun, 15 Dec 2019 17:32:39 +0100

Currently, the lambda capture is defined as:


       & identifier

I wonder if it might make sense to (1) change this so that attributes
are allowed and (2) allow maybe_unused for lambda captures.

The motivation for this can be seen in the following code, where `foo`
increments `a` depending on the template parameter:

     #include <iostream>
     #include <type_traits>

     template <bool Enable>
     int foo() {
       int a = 0;
       [&a]() {
         if constexpr (Enable) {
       return a;

     int main() {
       std::cout << foo<true>() << std::endl; // prints 1
       std::cout << foo<false>() << std::endl; // prints 0

As the `foo<false>` instantiation disables the `++a` part, clang
currently emits a warning:

     capture.cpp:7:5: warning: lambda capture 'a' is not used
       [&a]() {

With the proposed change, we could change the lambda to

       [ [[maybe_unused]] &a]() {

Besides this example, other motivations that were originally brought
forward for maybe_unused (including assert / NDEBUG) apply.

This would be similar to
where maybe_unused allowed for structured bindings.

Any thoughts on this? Is there a syntactical / logical reason why this
does not make sense? Also, as I am not too familiar with the C++
decision making process - any idea where one might find information on
whether this was already considered?


P.S.: I previously posted this on StackOverflow, where this discussion
was considered off-topic as it does not relate to today's C++:

Received on 2019-12-15 10:35:06