Lambda And Templates

Generic Lambda (auto Parameters)

  • auto is cool! One wouldn’t expect how simple templates could be!

#include <iostream>

int main()
{
    auto add = [](auto lhs, auto rhs) {
        return lhs + rhs;
    };

    std::cout << add(1, 2) << '\n';
    return 0;
}
  • Abbreviated function templates: the same, but with regular function templates instead (no lambda)

#include <iostream>

auto add(auto lhs, auto rhs) {
    return lhs + rhs;
};

int main()
{
    std::cout << add(1, 2) << '\n';
    return 0;
}

Template Lambda (C++20)

  • Re-unification: generic lambda vs. template lambda

#include <iostream>

int main()
{
    auto add = []<typename LHS, typename RHS>(LHS lhs, RHS rhs) {
        return lhs + rhs;
    };

    std::cout << add(1, 2) << '\n';
    return 0;
}