如何替换此代码中的 auto 关键字?

CaT*_*aTx 0 c++ variables types auto

我正在关注这个教程main.cc中的以下声明引起了我的兴趣:

auto say_hello = [](const HttpRequest& request) -> HttpResponse {
    HttpResponse response(HttpStatusCode::Ok);
    response.SetHeader("Content-Type", "text/plain");
    response.SetContent("Hello, world\n");
    return response;
}
Run Code Online (Sandbox Code Playgroud)

图像

这显示在调试窗口中。

auto我希望用原始数据类型替换关键字。我已尝试以下操作但失败:

HttpResponse say_hello = [](const HttpRequest& request) -> HttpResponse {...}
Run Code Online (Sandbox Code Playgroud)

有人能告诉我为什么这是错误的吗?正确的解决方案是什么?太感谢了!!!

rce*_*pre 5

我认为在使用 lambda 时了解以下 3 种方法很重要。这三个第一本质上做的是相同的事情:存储 lambda 以供将来使用。另一个似乎是您对代码的期望:您直接调用 lambda 并获取结果,因此返回类型是 lambda 返回的类型。

#include <iostream>
#include <functional>

int main()
{
    // Auto store the lambda
    auto auto_keyword = [](int a) -> int
    { return a; };
    std::cout << auto_keyword(42) << std::endl;

    // std::function store the lambda
    std::function<int(int)> std_function = [](int a) -> int
    { return a; };
    std::cout << std_function(42) << std::endl;

    // raw function pointer
    int (*raw_fptr)(int) = [](int a) -> int
    { return a; };
    std::cout << raw_fptr(42) << std::endl;

    // direct call to the lambda. (what you expect from your question)
    std::cout << ([](int a) -> int{ return a; })(42) << std::endl;
    
    return 0;
}

Run Code Online (Sandbox Code Playgroud)

这里发生了很多事情,我建议您至少阅读参考资料中的这一页,以便更好地理解。