C++11 lambda function definition in if-else

情到浓时终转凉″ 提交于 2020-04-07 04:14:34

问题


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]; };
}

回答1:


The auto b; and auto g; would need to be initialised so that the compiler would be able to determined their type (but I think you know this).

Since you don't seem to mind the specifics of type (you've declared them auto anyway);

std::function<bool(int,int)> b;
std::function<int&(int,int)> g;

Should do the trick.




回答2:


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.



来源:https://stackoverflow.com/questions/25302921/c11-lambda-function-definition-in-if-else

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!