Can I Declare a Lambda Later in C++?

0
0
Asked By CodeNinja42 On

Hey folks! I'm working on a function where I need to set up a compare function based on certain conditions in C++. I thought I could do this cleanly by declaring a lambda like this:

```c++
vector<long> myFunc(args...){
...
bool temp_cmp;
if (condition01) {
temp_cmp = [&](long i1, long i2) { return i1 < i2; };
} else if (condition02) {
temp_cmp = [&](long i1, long i2) { return i1 > i2; };
}
...
}
```

But I'm getting this error that says `no suitable conversion function from "lambda [](ull i1, ull i2)->bool" to "bool" exists` when I try to use `temp_cmp` after `condition01`. So my question is, is there a way to declare a lambda function inside an if-statement and use it later outside of that block?

I also realized that the error is linked to me trying to give the lambda function a return type of `bool` directly, which only adds to the confusion. Any advice would be much appreciated!

1 Answer

Answered By LambdaMaster99 On

Here’s the thing: a `bool` and a function that returns a `bool` are two different types! Each lambda has its own unique type, so you can’t just assign it to a `bool`. If you want the flexibility to hold different lambdas, use `std::function`. Check out this example: https://godbolt.org/z/GxYarrqej

CodeNinja42 -

Thanks a lot! I get it now—so `std::function` is my friend here. I assumed a function's return type could be directly treated as its type, but I see that it's not quite that simple.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.