20

I am passing a lambda with an init-captured loop counter like this:

#include <iostream>

auto sq(int c, int x) { return c * x * x; }

struct S {
    template<class Fun>
    void for_each(Fun fun) const {
        for (auto i = 1; i < 4; ++i) {
            fun(i);    
        }
    }    
};

int main()
{
    S s;
    auto sum = 0;
    s.for_each([&, i = 2](auto c) mutable {
        sum += sq(c, i++);    
    });
    std::cout << sum;   // 70 = 1 * 4 + 2 * 9 + 3 * 16
}

For g++ up to 7.0 SVN and for clang++ up to 3.9.1, this all compiles warning-free. However, for clang++ 5.0 SVN, I get

prog.cc:18:20: warning: lambda capture 'i' is not required to be captured for this use [-Wunused-lambda-capture]
    s.for_each([&, i = 2](auto c) mutable {

even though it still prints out the correct answer. Live Example

Question: why am I getting this new Wunused-lambda-capture warning from clang?

TemplateRex
  • 69,038
  • 19
  • 164
  • 304

1 Answers1

16

Your code is valid.

Clang's warning is nonsense.

Report this as a bug.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524