Reputation: 463
I am just exploring lambda expression and trying to use it to return from a function using C++ ternary operator. However the below code does not work with error!
this is a simplified version of the program to explain my actual problem so kindly post answer using a lambda only, not just return (x+y+offset).
In member function 'int Calculator::add(int, int)': 12:26: error: no match for ternary 'operator?:' (operand types are 'bool', 'int', and 'Calculator::add(int, int)::<lambda()>') 16:3: warning: control reaches end of non-void function [-Wreturn-type]
#include <iostream>
#include <string>
class Calculator
{
public:
bool initalized = false;
int offset = 0;
int add(int x, int y)
{
return !initalized ? -1 : [this, x, y]()
{
return ((x+y) + offset);
};
}
};
int main()
{
Calculator c;
c.initalized = true;
c.offset = 1;
printf("%d", c.add(2,10));
}
What am I doing wrong here?
Upvotes: 0
Views: 284
Reputation: 206607
What am I doing wrong here?
The true/false parts of the ternary expression are not compatible. You cannot convert -1
to a lambda expression and you cannot convert the lambda expression to an int
.
It's not clear to me what you are trying to do with the lambda expression but it can be:
return !initalized ? -1 : (x + y + this->offset);
If you have the need to use a lambda expression for some reason, you'll have to invoke the lambda expression.
return !initalized ? -1 : [this, x, y]() { return ((x+y) + this->offset); }();
// missing ^^
Upvotes: 0
Reputation: 13760
Your ternary operator tries to return -1 or a lambda, which do not have a common type.
You need to actually call the lambda:
return !initalized ? -1 : [this, x, y]()
{
return ((x+y) + offset);
}(); // <= added ()
Or without a lambda:
return !initalized ? -1 : x+y+offset;
Upvotes: 2