[Home]Problems - Lambda Library

BOOST WIKI | RecentChanges | Preferences | Page List | Links List

This page is for discussion of problems with the Boost Lambda Library (e.g. bugs)

Back to lambda library pages


How to access member variables in lambda functor?

I'm trying to figure out how to do something like this:

    for_each(container.begin(), container.end(), cout << _1.member << "\n");

which is obviously wrong, but hopefully you know what I mean...

Experimenting with ways of accessing members inside a lambda, I wrote the following:

    #include <iostream>
    #include <boost/lambda/lambda.hpp>
    #include <vector>

    using namespace std;
    using namespace boost;
    using namespace lambda;

    struct XX {
        XX(int a, int b) { a_ = a; b_ = b; }
        int a_;
        int b_;
    };

    int main() {
        XX xx(5, 6);
        XX *xxp = &xx;

        cout << "These are all equivalent:\n";
        cout << xxp ->* &XX::a_ << endl;
        cout << (_1 ->* &XX::a_)(xxp) << endl;
        //cout << (_1 ->* &XX::a_)(&xx) << endl;                 // Doesn't compile!
        cout << (&_1 ->* &XX::a_)(xx) << endl;

        cout << "Now, let's try with the vector:\n";

        vector<XX> xxVec;
        xxVec.push_back(XX(3, 4));

        cout << (&_1 ->* &XX::a_)(xxVec[0]) << endl;
        //cout << (_1 ->* &XX::a_)(&xxVec[0]) << endl;           // Doesn't compile!
        cout << (_1 ->* &XX::a_)(xxp = &xxVec[0]) << endl;       // Now it compiles...
        //cout << (_1 ->* &XX::a_)(xxVec.begin()) << endl;       // Doesn't compile!
        //cout << (_1 ->* &XX::a_)(&*xxVec.begin()) << endl;     // Still not...
        cout << (_1 ->* &XX::a_)(xxp = &*xxVec.begin()) << endl; // Now it compiles...

        exit(0);
    }

I'm mystified by why some of these lines don't compile (gcc 3.2.2). Can anyone explain it? The compiler generates some horrific error messages -- I haven't tried to pick through them yet...

    - People/Chuck Messenger


BOOST WIKI | RecentChanges | Preferences | Page List | Links List
Edit text of this page | View other revisions
Last edited May 21, 2003 5:23 am (diff)
Search:
Disclaimer: This site not officially maintained by Boost Developers