Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 lambda function definition in if-else

How do I do something like this, but in a way that will compile, and hopefully without insane typedefs?

auto b;
auto g;
if (vertical)
{
    b = [=, &b_](int x, int y) -> bool { return b_[x + y*w]; };
    g = [=, &g_](int x, int y) -> int& { return g_[x + y*w]; };
}
else
{
    b = [=, &b_](int x, int y) -> bool { return b_[y + x*w]; };
    g = [=, &g_](int x, int y) -> int& { return g_[y + x*w]; };
}
like image 504
Timmmm Avatar asked Dec 11 '22 04:12

Timmmm


1 Answers

The reason this does not compile is the improper use of auto. You can avoid conditional creation of lambdas altogether by changing their definition a little:

int mx = vertical ? 1 : w;
int my = vertical ? w : 1;
auto b = [=, &b_](int x, int y) -> bool { return b_[mx*x + my*y]; };
auto g = [=, &g_](int x, int y) -> int& { return g_[mx*x + my*y]; };

The idea is to set multipliers mx and my conditionally. This lets you construct your lambdas unconditionally, so you could use auto in your declaration.

like image 94
Sergey Kalinichenko Avatar answered Dec 27 '22 23:12

Sergey Kalinichenko