Skip to content

Generic Lambdas (C++14) ​

In a Nutshell ​

Lets lambda expression parameters take auto, sparing us the hassle of writing multiple overloads for different types — it is equivalent to generating a templated operator().

None (language feature)

Core API Quick Reference ​

OperationSignatureDescription
Generic parameters[captures](auto a, auto b) { ... }Declare parameters with auto; a templated operator() is generated from the deduced types
Forwarding reference parameters[captures](auto&&... ts) { ... }Combine auto&& with perfect forwarding of the parameter pack
Explicit template parameters (C++20)[captures]<class T>(T a) { ... }Declare template parameters explicitly in angle brackets after the square brackets; supports constraints
No-capture function pointer conversionusing F = ret(*)(params); operator F() const;Capture-less generic lambdas convert implicitly to a function pointer (constexpr since C++17)

Minimal Example ​

C++
#include <iostream>
// Standard: C++14
int main() {
    auto compare = [](auto a, auto b) { return a < b; };
    std::cout << compare(3, 4) << "\n";       // int vs int
    std::cout << compare(3.14, 2.72) << "\n"; // double vs double
}

Embedded Suitability: High ​

  • Zero runtime overhead: auto is deduced purely at compile time, and the generated code is identical to a hand-written template
  • A great fit for generic callbacks (sorting comparators, timer callbacks, and the like), cutting down template code redundancy
  • The C++14 auto syntax is already widely supported by GCC 5+ / Clang 3.4+, so every mainstream embedded toolchain can use it

Compiler Support ​

GCCClangMSVC
5.03.419.0

See Also ​


Some content references cppreference.com, used under the CC-BY-SA 4.0 license

pdf-latest-4-g85128cc · 85128cc · 2026-10-05