Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have recently upgraded my g++ so I can enjoy lambda functions. Everything is great and I am very thankful to those who made it possible in C++ and gcc in particular. There is only one thing that I can't seem to solve - how to have lambda's arguments to be templated? Below are basic examples of lambda usage to demonstrate the problem.

Example #1, everything 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, assume that do_work now invokes predicate two times with different argument types. So here goes 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 auto keyword. I also tried templating it in-place. Don't try to compile that 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.

But you get the idea. I can solve it with new function declaration style, in theory, but that's not the point. Here is what I really am trying to do, but with simplified syntax (foo, bar and do_work are stripped for simplicity sake):

struct pred_t {
    pred_t () = default;

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

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

Is there a way, or at least plans, to add support for not fully specialized lambda functions, so that they will act sort of like a predicate with template <typename T> operator () (T &&)? I don't even know how to name it, lambda predicate maybe? Please let me know your thoughts! Thanks!


1 Answers

These were discussed as "polymorphic lambdas", and were declined because it made problems with the concepts proposal.

Last year 2009 at the Frankfurt meeting, the concepts proposal was voted out of the working paper, but polymorphic lambdas weren't considered anymore for C++0x.

See C++0x and the Lack of Polymorphic Lambdas.

like image 166
Johannes Schaub - litb Avatar answered Nov 29 '25 20:11

Johannes Schaub - litb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!