【问题标题】:Can I call a lambda without first assigning it to a variable?我可以在不先将其分配给变量的情况下调用 lambda 吗?
【发布时间】:2018-03-11 23:33:35
【问题描述】:

我正在学习如何使用 lambda 函数。如果没有分配给变量,为什么我的最后一个 lambda 不会自动运行?之前所有的都按预期工作。

#include "stdafx.h"
#include <iostream>
#include <thread>
using namespace std;
int main()
{
    std::thread t([]() {
        std::cout << "thread function\n";
    });
    std::cout << "main thread\n";
    t.join();

    auto a = []() -> int {
        return 1 + 2;
    };
    int n = a();
    cout << n << endl;

    auto b = []() -> void {
        cout << "sup" << endl;
    };
    b();

    //why doesn't this run automatically?
    []() -> void {
        cout << "hellur!" << endl;
    };

    return 0;
}

【问题讨论】:

  • 因为你不叫它。
  • 我可以在不先将其分配给变量的情况下调用 lambda 吗?
  • 是的,使用函数调用运算符()
  • ...您为什么会出于好奇而这样做?为什么不简单地在其中包含实际代码而不是 lambda?

标签: c++11 lambda


【解决方案1】:

解决方案:

[]() -> void {
    cout << "hellur!" << endl;
}();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-24
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    相关资源
    最近更新 更多