jeudi 2 juin 2016

std::find_if and lambda referencing structure field

In this question we have:

#include <list>
#include <algorithm>

struct S
{
    int S1;
    int S2;
};

int main()
{
    std::list<S> l;
    S s1;
    s1.S1 = 0;
    s1.S2 = 0;
    S s2;
    s2.S1 = 1;
    s2.S2 = 1;
    l.push_back(s2);
    l.push_back(s1);

    std::list<S>::iterator it = std::find_if(l.begin(), l.end(), [] (S s)
        { return s.S1 == 0; } );
}

But, if I want to find a match for s1.S1, I might try:

std::list<S>::iterator it = std::find_if(l.begin(), l.end(), [s1.S1] (S s)
    { return s.S1 == s1.S1; } );

I get a compiler error, however. This works:

auto foo = s1.S1;
std::list<S>::iterator it = std::find_if(l.begin(), l.end(), [foo] (S s)
    { return s.S1 == foo; } );

I think I understand why I need to introduce a temporary simple type as we can think of the [foo] as like a function parameter, but the use case of looking up a structure member would seem to be a frequent requirement, so what is the rationale for not supporting the usage? Or is there another way to avoid the temporary variable?

Aucun commentaire:

Enregistrer un commentaire