Advertisement
Intermediate C++, Lambda Expressions

How do you specify a lambda's return type?

Short answer

Usually the return type is deduced from the return statements. When deduction is ambiguous or you want an explicit type, use a trailing return type: [](int x) -> double { ... }.

Save C++ mock interview
Advertisement
AModel answer
Usually the return type is deduced from the return statements. When deduction is ambiguous or you want an explicit type, use a trailing return type: [](int x) -> double { ... }. Explicit return types are also needed when different return statements would otherwise deduce different types.
auto f = [](int x) -> double {
    if (x > 0) return x;   // int
    return 0.5;            // double -> need explicit type
};
Real-world example
An explicit -> double return type resolves a lambda that returns both int and double literals.
Likely follow-ups
  • When must you specify the return type? | How is it deduced by default?
Related topics