Search code examples
c++templateslambdaboostfunction-declaration

How does compiler deduce return type from this lambda expression?


I am creating a web-socket server in C++ with Boost library. My starting point was a Boost example from this site. I have a question with this part of code in the on_run method:

 ws_.set_option(websocket::stream_base::decorator(
            [](websocket::response_type& res)
            {
                res.set(http::field::server,
                    std::string(BOOST_BEAST_VERSION_STRING) +
                        " websocket-server-async");
            }));

As it can seen, ws_.set_option takes a websocket::stream_base::decorator as a parameter and this parameter is created by a lambda expression, which takes a Decorator&& type variable as a parameter according to this site.

How does the lambda expression know, it should return a Decorator&&, when there is no trailing-return-type or return statement in the lambda expression? Last, but no least, where does the websocket::response_type &res come from? There is no () including this parameter after the lambda body.


Solution

  • websocket::stream_base::decorator is a template function with one template type parameter.

    template<class Decorator>
    decorator( Decorator&& f );
    

    In this call

    ws_.set_option(websocket::stream_base::decorator(
            [](websocket::response_type& res)
            {
                res.set(http::field::server,
                    std::string(BOOST_BEAST_VERSION_STRING) +
                        " websocket-server-async");
            }));
    

    the function is called accepting the lambda expression

    [](websocket::response_type& res)
            {
                res.set(http::field::server,
                    std::string(BOOST_BEAST_VERSION_STRING) +
                        " websocket-server-async");
            }
    

    as its template argument. The lambda expression has by default the return type void because there is no return statement in the lambda expression.

    How does the lambda expression know, it should return a Decorator&&

    It is the lambda expression itself is used as an argument for the declared function template parameter Decorator&&.