Rule A5-1-9 (advisory, implementation, automated)

Identical unnamed lambda expressions shall be replaced with a named function or a named lambda expression.

Rationale

Code duplication reduces readability and maintainability as it might not be obvious that the lambda expressions are identical and any changes need to be applied in more than one place.

Example

// $Id: A5-1-9.cpp 307019 2018-02-09 15:16:47Z christof.meerwald $
#include <algorithm>
#include <cstdint>
#include <vector>

void Fn1(const std::vector<int16_t> &v)
{
// Non-compliant: identical unnamed lambda expression
if (std::none_of(v.begin(), v.end(),
[] (int16_t i) { return i < 0; }))
{
// ...
}
else if (std::all_of(v.begin(), v.end(),
[] (int16_t i) { return i < 0; }))
{
// ...
}
}

void Fn2(const std::vector<int16_t> &v)

{
// Compliant: re-using lambda expression
auto is_negative = [] (int16_t i) { return i < 0; };

if (std::none_of(v.begin(), v.end(), is_negative))
{
// ...
}
else if (std::all_of(v.begin(), v.end(), is_negative))
{
// ...
}

}

See also

C++ Core Guidelines [11]: T.141: Use an unnamed lambda if you need a simple function object in one place only.