Quick Q: A lambda’s return type can be deduced, so why can’t a function’s?—StackOverflow

Save to:
Instapaper Pocket Readability

Quick A: It can, in C++14. In fact, this C++14 feature supported today in current versions of GCC and Clang with -std-c++1y and in the Visual C++ November 2013 CTP.

On SO:

A lambda's return type can be deduced by the return value, so why can't a function's?

#include <iostream>

int main(){

    auto lambda = [] {
        return 7;
    };

    std::cout << lambda() << '\n';

}

This program compiles and prints 7.
The return type of the lambda is deduced to the integer type based on the return value of 7.

Why isn't this possible with ordinary functions?

#include <iostream>

auto function(){
    return 42;
}

int main(){

    std::cout << function() << '\n';
}

error: ‘function’ function uses ‘auto’ type specifier without trailing return type

Add a Comment

You must sign in or register to add a comment.

Comments (0)

There are currently no comments on this entry.