C ++ 0x template lambda function ... or functor / predicate?

I recently updated my g++so that I can use the lambda functions. Everything is fine, and I am very grateful to those who made this possible in C ++ and gcc in particular. There is only one thing that I can't seem to solve - how do I have lambda pattern templates? The following are basic examples of using lambda to demonstrate the problem.

Example # 1, all this is yummy:

#include <cstdio>

struct bar {
    bar () {}

    void say () {
        printf ("bar::say()\n");
    }

    void say () const {
        printf ("bar::say() const\n");
    }
};

template <typename T>
void do_work (const T & pred) {
    bar b;
    pred (b);
}

int main () {
    do_work ([] (bar & b) { b.say (); });
}

Now suppose that do_worknow calls the predicate two times with different types of arguments. So here is example # 2:

#include <cstdio>

struct foo {
    foo () {}

    void say () {
        printf ("foo::say()\n");
    }

    void say () const {
        printf ("foo::say() const\n");
    }
};

struct bar {
    bar () {}

    void say () {
        printf ("bar::say()\n");
    }

    void say () const {
        printf ("bar::say() const\n");
    }
};

template <typename T>
void do_work (const T & pred) {
    const foo f;
    bar b;
    pred (f);
    pred (b);
}

int main () {
    do_work ([] (auto & b) { b.say (); });
}

Note <keyword auto. I also tried to fix it in place. Do not try to compile this with gcc, here is what I get:

./test.cpp:31:5: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <http://gcc.gnu.org/bugs.html> for instructions.

. , , . , (foo, bar do_work ):

struct pred_t {
    pred_t () = default;

    template <typename T>
    void operator () (T && obj) const {
        obj.say ();
    }
};

int main () {
    do_work (pred_t ());
}

, , , -, template <typename T> operator () (T &&)? , , -, ? , ! !

+3
2

" " , .

2009 , lambdas ++ 0x.

. ++ 0x .

+5
do_work ([] (auto & b) { b.say (); });

, auto function/lambda.

+1

All Articles