Ray's Knowledge Base
Unlock

Clang calls this unused in a generic lambda that calls a member without this->

PitfallVerified 28 Sep 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

In a class template, a generic lambda that captures this and calls a member function draws a warning, although it does use this:

Value operator()(const Term& t) const {
    return std::visit([this](const auto& n) { return node(n); }, t.node);
}
warning: lambda capture 'this' is not used [-Wunused-lambda-capture]

With warnings treated as errors, or a no-warnings rule, the build fails.

Cause#

Inside the generic lambda of a template, node(n) is a call that depends on the lambda's auto parameter, and clang's unused-capture check does not count the implicit this it goes through. Why clang misses it was not investigated; the call does need the capture.

Fix#

Name the member through this:

return std::visit([this](const auto& n) { return this->node(n); }, t.node);

Do not drop the capture: the call needs it.

Evidence#

  • dftracer-utils src/dftracer/utils/duql/evaluator.cpp, TermEval<Record>::operator() (Apple clang, C++20, 2026-09-27): the warning appeared on every instantiation and went away with this->node(n); the same fix removed it for a generic lambda calling intern_lookup in event_source.h.

Also found by searching

  • warning: lambda capture 'this' is not used [-Wunused-lambda-capture] in std::visit generic lambda calling member
  • clang says this capture is unused even though my lambda calls a member function, build fails with -Werror
  • how do I silence unused this capture in a generic lambda inside a class template without removing it
  • auto parameter lambda dependent call implicit this, clang false positive, write this->node(n)
  • warning: lambda capture 'this' is not used [-Wunused-lambda-capture] in generic lambda inside template std::visit
  • clang says this unused but my lambda calls a member function, treated as error
  • how do I fix unused-lambda-capture warning for this in a template class visitor
  • std::visit generic lambda [this] const auto& n node(n) clang warning vs gcc