正常
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().
Header
None (language feature)
Core API Quick Reference
| Operation | Signature | Description |
|---|---|---|
| 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 conversion | using 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:
autois 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
autosyntax is already widely supported by GCC 5+ / Clang 3.4+, so every mainstream embedded toolchain can use it
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 5.0 | 3.4 | 19.0 |
See Also
Some content references cppreference.com, used under the CC-BY-SA 4.0 license