Error: variable “cannot be implicitly captured because no default capture mode has been specified”

后端 未结 1 1175
南方客
南方客 2020-11-29 04:54

I am trying to follow this example to use a lambda with remove_if. Here is my attempt:

int flagId = _ChildToRemove->getId();
auto new_end =          


        
相关标签:
1条回答
  • 2020-11-29 05:31

    You must specify flagId to be captured. That is what the [] part is for. Right now it doesn't capture anything. You can capture (more info) by value or by reference. Something like:

    auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
            [&flagId](Flag& device)
        { return device.getId() == flagId; });
    

    Which captures by reference. If you want to capture by const value, you can do this:

    auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
            [flagId](Flag& device)
        { return device.getId() == flagId; });
    

    Or by mutable value:

    auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
            [flagId](Flag& device) mutable
        { return device.getId() == flagId; });
    

    Sadly there is no straightforward way to capture by const reference. I personally would just declare a temporary const ref and capture that by ref:

    const auto& tmp = flagId;
    auto new_end = std::remove_if(m_FinalFlagsVec.begin(), m_FinalFlagsVec.end(),
                [&tmp](Flag& device)
            { return device.getId() == tmp; }); //tmp is immutable
    
    0 讨论(0)
提交回复
热议问题