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

时间:2013-12-31 06:20:13

标签: 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..

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

2 个答案:

答案 0 :(得分:6)

在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

答案 1 :(得分:1)

实际上,代码段之间存在两个差异:

  1. 一个代码段在lambda立即执行它之后有一个括号,在使用long后产生g_Frequency并且没有括号,只是读取它的值。
  2. 另一个代码段在lambda之后没有括号,即g_Frequency成为函数对象,并且在使用g_frequency之后有一个括号,使其成为对函数的调用。 / LI>