加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C lambda后跟()vs. lambda没有()

发布时间:2020-12-16 09:49:46 所属栏目:百科 来源:网络整理
导读:这两段代码有什么区别? struct HighResClock{ typedef long long rep; typedef std::nano period; typedef std::chrono::durationrep,period duration; typedef std::chrono::time_pointHighResClock time_point; static const bool is_steady = true; stat
这两段代码有什么区别?

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次.括号是什么意思,它有什么作用?括号中是否有此语法的名称?

解决方法

在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读