Search code examples
visual-c++lambdac++14pass-by-reference

Using alias for referenced variables in capture list of lambda?


With a lambda, is it not possible to use an alias for a variable that is in the capture list (by reference)?

auto AddSlip = [rFile = &fileCSV](COleDateTime datMeeting)
{

}

That won't work.


Solution

  • With a lambda, is it not possible to use an alias for a variable that is in the capture list (by reference)?

    Yes: it's possible. Starting from C++14.

    Not in your way

    auto AddSlip = [rFile = &fileCSV](COleDateTime datMeeting)
    

    because rFile become the copy of the pointer to fileCSV; the syntax you're looking for is the following

    auto AddSlip = [&rFile = fileCSV](COleDateTime datMeeting)
    

    or, if you want a const reference,

    auto AddSlip = [&rFile = std::as_const(fileCSV)](COleDateTime datMeeting)