C++ lambda 后跟 () 与没有 () 的 lambda

标签 c++ lambda

这两段代码有什么区别?

struct HighResClock
{
    typedef long long                               rep;
    typedef std::nano                               period;
    typedef std::chrono::duration<rep, period>      duration;
    typedef std::chrono::time_point<HighResClock>   time_point;
    static const bool is_steady = true;

    static time_point now();
};


namespace
{
    auto g_Frequency = []() -> long long
    {
        std::cout<<"HERE";
        LARGE_INTEGER frequency;
        QueryPerformanceFrequency(&frequency);
        return frequency.QuadPart;
    }();
}

HighResClock::time_point HighResClock::now()
{
    LARGE_INTEGER count;
    QueryPerformanceCounter(&count);
    return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency));
}

int main()
{
    HighResClock c;
    c.now();
    c.now();
    c.now();
}

struct HighResClock
{
    typedef long long                               rep;
    typedef std::nano                               period;
    typedef std::chrono::duration<rep, period>      duration;
    typedef std::chrono::time_point<HighResClock>   time_point;
    static const bool is_steady = true;

    static time_point now();
};


namespace
{
    auto g_Frequency = []() -> long long
    {
        std::cout<<"HERE";
        LARGE_INTEGER frequency;
        QueryPerformanceFrequency(&frequency);
        return frequency.QuadPart;
    };
}

HighResClock::time_point HighResClock::now()
{
    LARGE_INTEGER count;
    QueryPerformanceCounter(&count);
    return time_point(duration(count.QuadPart * static_cast<rep>(period::den) / g_Frequency()));
}

int main()
{
    HighResClock c;
    c.now();
    c.now();
    c.now();
}

如果你没有注意到,不同之处在于下面的括号:

auto g_Frequency = []() -> long long
{
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    return frequency.QuadPart;
}(); //this bracket here appears in one and not the other..

我问是因为带括号的只打印一次“这里”,而另一个(没有括号)打印 3 次。括号是什么意思,它有什么作用?这种带括号的语法有名称吗?

最佳答案

在 lambda 定义 []{}(); 之后立即写入 () 将调用 lambda,因此结果是 lambda 返回类型的类型.

如果省略 () 后缀,将返回一个 lambda 类型(未指定),它基本上是一个可调用仿函数。

auto result = []{ return 42; }(); // auto is integer, result has 42 in it  
auto result1 = []{ return 42; }; // auto is some unspecified lambda type  
auto result2 = result1(); // auto is integer, result2 is storing 42` 
......................^^ - this is the bracket you can also put directly after the definition of the lambda

关于C++ lambda 后跟 () 与没有 () 的 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20852806/

相关文章:

c++ - memset 和 std::complex<double> 的动态数组

c++ - "vector iterator not incrementable"set_intersection 运行时错误

c++ - 如何定义静态运算符<<?

function - Kotlin:通用函数作为返回类型?

使用 lambda 的 Python 闭包

c++ - 指向带有模板参数的函数的指针

c++ - Qt:qmake中VERSION和VER_MAJ、VER_MIN、VER_PAT的区别

c# - 动态表达返回类型Lambda表达式

c# - 身份 2.2.1 中具有角色列表的用户列表

Java 8 : How to sort and collect two nested Maps with ArrayList inside?