4 years, 12 months ago.

How do I assign a lambda (anonimous) function to a variable?

I'm trying to assign a function to a variable without the function declaration.

So this code is compiling:

    void foo(void) {
        a++;
    }

    typedef void (*tCallBack)();
    tCallBack cb;
    cb = &foo;

However this code has extra lines and not very readable as the action declared in the separate place (outside of main). So I'd like to do something like this:

    typedef void (*tCallBack)();
    tCallBack cb;
    cb = [](){ a++; };

But the compiller throws an error: Error: Expected an expression in "main.cpp", Line: 254, Col: 25

The syntax [](){} is taken from wikipedia and should work for C++ 11 and above. As I know - MBED uses C++ 11 so it should work.

Any thoughts?

Question relating to:

ST
A world leader in providing the semiconductor solutions that make a positive contribution to people’s lives, both today and in the future.

2 Answers

4 years, 12 months ago.

I don't think so it is complicated, but don't worry if you can't do it yourself. You can get web development services web development services from a digital company to solve out your issue. I am sure you will easily find this solution.

4 years, 12 months ago.

Hello Roman,

This example could help.

Hi, Zoltan! Just read this topic with all the comments and there stated that MBED compiller does not support constructions like that. So it is not possible in MBED online compiller? Or I get it wrong?

posted by Roman Matveev 30 Mar 2019

Although I haven't tried it yet, maybe you can modify the build profile (set "-std=gnu++11") of your online project/compiler as described here.

posted by Zoltan Hudak 30 Mar 2019