Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to inline a lambda expression? [duplicate]

I want to inline a lambda expression since it is very short for performance reason. Is it possible?

like image 621
Thomson Avatar asked Jul 22 '10 13:07

Thomson


People also ask

Can lambdas be Constexpr?

constexpr lambda expressions in C++ Visual Studio 2017 version 15.3 and later (available in /std:c++17 mode and later): A lambda expression may be declared as constexpr or used in a constant expression when the initialization of each data member that it captures or introduces is allowed within a constant expression.

Is lambda function same as inline function?

All lambdas definitely are NOT inline. But all lambdas definitely are inplace. The inline is reserved for the compiler specific optimization which is not much correlated with the inplace coding like lambdas does.

How do you write lambda in copy?

Lambda Symbol (λ)

What is a mutable lambda?

The mutable keyword is used so that the body of the lambda expression can modify its copies of the external variables x and y , which the lambda expression captures by value. Because the lambda expression captures the original variables x and y by value, their values remain 1 after the lambda executes. C++ Copy.


2 Answers

The inline keyword does not actually cause functions to be inlined. Any recent compiler is going to make better decisions with regards to inlining than you will.

In the case of a short lambda, the function will probably be inlined.

If you're trying to use the inline keyword with a lambda, the answer is no, you can't use that.

like image 97
Billy ONeal Avatar answered Oct 13 '22 18:10

Billy ONeal


The compiler will inline it if it can. For example, in g++ 4.5 with -O2,

#include <vector>
#include <algorithm>

int main () {
    std::vector<int> a(10);
    for (int i = 0; i < 10; ++ i) a[i] = i;

    asm ("Ltransform_begin: nop; nop; nop; nop; nop; nop; ");
    std::transform(a.begin(), a.end(), a.begin(), [] (int x) { return 2*x; });
    asm ("Lforeach_begin: nop; nop; nop; nop; nop; nop; ");
    std::for_each(a.begin(), a.end(), [] (int x) { printf("%d\n", x); });
    asm ("Lforeach_done: nop; nop; nop; nop; nop; nop; ");

    return 0;
}

generates the assembly that the 2*x and printf lambdas are completely inlined.

# 9 "x.cpp" 1
    Ltransform_begin: nop; nop; nop; nop; nop; nop; 
# 0 "" 2
    .align 4,0x90
L13:
    sall    (%rax)
    addq    $4, %rax
    cmpq    %rax, %r12
    jne L13
# 13 "x.cpp" 1
    Lforeach_begin: nop; nop; nop; nop; nop; nop; 
# 0 "" 2
    .align 4,0x90
L14:
    movl    (%rbx), %esi
    leaq    LC0(%rip), %rdi
    xorl    %eax, %eax
LEHB1:
    call    _printf
LEHE1:
    addq    $4, %rbx
    cmpq    %r12, %rbx
    jne L14
# 17 "x.cpp" 1
    Lforeach_done: nop; nop; nop; nop; nop; nop; 
# 0 "" 2
like image 45
kennytm Avatar answered Oct 13 '22 20:10

kennytm