5

Lambdas are an awesome way to create reusable code inside a function/method without polluting the parent class. They're a very functional replacement for C-style macros most of the time.

However, there's one bit of syntactic sugar from macros that I can't seem to replicate with a lambda, and that's the ability to exit from the containing function. For example, if I need to return while checking the range of a series of ints, I can do that easily with a macro:

const int xmin(1), xmax(5);
#define CHECK_RANGE(x) { if((x) < xmin || (x) > xmax) return false; }

bool myFunc(int myint) {
    CHECK_RANGE(myint);
    int anotherint = myint + 2;
    CHECK_RANGE(anotherint);
    return true;
}

Obviously this is an oversimplified example, but the basic premise is that I'm performing the same check over and over on different variables, and I think it's more readable to encapsulate the check and related exits. Still, I know that macros aren't very safe, especially when they get really complex. However, as far as I can tell, trying to do the equivalent lambda requires awkward additional checks like so:

const int xmin(1), xmax(5);
auto check_range = [&](int x) -> bool { return !(x < xmin || x > xmax); };

bool myFunc(int myint) {
    if(!check_range(myint)) return false;
    int anotherint = myint + 2;
    if(!check_range(anotherint)) return false;
    return true;
}

Is there a way to do this with a lambda? Or am I missing some alternative solution?

Edit: I recognize that returning from inside a macro is generally a bad idea unless significant precautions are taken. I'm just wondering if it's possible.

9
  • 2
    there's one bit of syntactic sugar - yes, to make the code incomprehensible.
    – user2672107
    Commented Jul 31, 2017 at 22:09
  • No, this isn't possible. It would be nice if there were some way to do this, but there is not as of this time
    – Justin
    Commented Jul 31, 2017 at 22:12
  • 2
    I'll side with Justin before thinking too much about how std::longjmp could help.
    – Quentin
    Commented Jul 31, 2017 at 22:15
  • @Quentin I'll prefer macros to longjmp. But actually, the only bad thing about macro is that it doesn't check types and syntax. macro generates source code your compiler process after, there is NO insecurity if macro used right. There are pitfalls in way how you write macro, e.g. parameters being reused with incremental operator.. or absence of parents around those expressions. Commented Jul 31, 2017 at 22:27
  • 1
    However, there's one bit of syntactic sugar... -- that's a funny way of spelling "thankfully"
    – rlbond
    Commented Jul 31, 2017 at 22:54

4 Answers 4

5

You are correct--there's no way to return from the caller from inside a lambda. Since a lambda can be captured and stored to be called later, from inside an arbitrary caller, doing so would result in unpredictable behavior.

class Foo
{
    Foo(std::function<void(int)> const& callMeLater) : func(callMeLater) {}
    void CallIt(int* arr, int count)
    {
        for (index = count; index--;)
            func(count);
        // do other stuff here.
    }
    std::function<void(int)> func;
};

int main()
{
    auto find3 = [](int arr) 
    {
        if (arr == 3)
            return_from_caller; // making up syntax here.
    };

    Foo foo(find3);
};
4

Is there a way to do this with a lambda?

Not exactly like the macro but your lambda, instead of returning a bool, can throw a special exception (of type bool, by example)

auto check_range
   = [](int x) { if ( (x < xmin) || (x > xmax) ) throw bool{false}; };

and the function myFunc() can intercept this special type

bool myFunc (int myint)
 {
   try
    {
      check_range(myint);
      int anotherint = myint + 2;
      check_range(anotherint);
      return true;
    }
   catch ( bool e )
    { return e; }
 }

For a single check_range() call, this is (I suppose) a bad idea; if you have a lot of calls, I suppose can be interesting.

The following is a full working example

#include <iostream>

constexpr int xmin{1}, xmax{5};

auto check_range
   = [](int x) { if ( (x < xmin) || (x > xmax) ) throw bool{false}; };

bool myFunc (int myint)
 {
   try
    {
      check_range(myint);
      int anotherint = myint + 2;
      check_range(anotherint);
      return true;
    }
   catch ( bool e )
    { return e; }
 }

int main ()
 {
   std::cout << myFunc(0) << std::endl; // print 0
   std::cout << myFunc(3) << std::endl; // print 1
   std::cout << myFunc(7) << std::endl; // print 0
 }
2
  • 2
    Rather than throw a bool, it is generally more preferred (and easier to read) to throw a custom struct/class instead, especially run that is derived from std::exception (like std::out_of_range or std::range_error), and then catch that instead and use return false directly. Commented Aug 1, 2017 at 0:08
  • 1
    +1 because this is the solution I'm looking for, but the accepted answer addresses the question itself better.
    – Phlucious
    Commented Aug 1, 2017 at 15:19
1

No better way to do this than just to use the return value of the lambda and then return from the calling function. Macros are ew for this.

As it stands in C++, that is the idiomatic way to exit from a function that uses another condition to determine whether or not to exit.

1

Not C++11, but people have hacked C++2a coroutines to basically do this.

It would look a bit like:

co_await check_range(foo);

where the co_await keyword indicates that in some cases, this coroutine could return early with an incomplete result. In your cases, this incomplete result would be non-resumabable error.

The playing around I saw was with optionals, and required using a shared ptr, but things may improve before it is standardized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.