4

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
  • 3
    Declare b and g as std::function objects? Commented Aug 14, 2014 at 8:05

2 Answers 2

7

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.

2
  • That's a nice solution.
    – Timmmm
    Commented Aug 14, 2014 at 8:20
  • I went with your solution in my code, but gave the tick to the other answer since this one is more of a workaround that only works with this specific example (a good workaround though). Thanks!
    – Timmmm
    Commented Aug 14, 2014 at 8:58
6

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
  • Repetition? In the declaration or the calculation?
    – Niall
    Commented Aug 14, 2014 at 8:23
  • The declaration. I.e. I have to mentally convert (int x, int y) -> int& to int& (int, int). Ok I guess it's not that bad and that's presumably the best C++11 can do, but I felt I might be missing a more elegant method.
    – Timmmm
    Commented Aug 14, 2014 at 8:57

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.