Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to conditionally select different initializer lists for a c++ ranged-for loop?

Tags:

c++

I would like to rearrange this code:

if (x_can_be_true) {
  for (x : {false, true}) {
    do_work(x);
  }
} else {
  do_work(false);
}

so do_work is called only once.

Conceptually, I would like to do this:

for (x : (x_can_be_true ? {false, true} : {false})) {
  do_work(x);
}

Any suggestions how to make that code actually compile?

EDITs: do_work is a simplified placeholder for the real-world problem. it's many lines of code that depend on many parameters from prior lines. the objective of the question is to find a pattern that avoids repeating those many lines. cause that's not-good coding practice. ;->

i could make it a function with many parameters. or use a parameter block. but... ick. ;->

like image 557
timmer Avatar asked Dec 24 '22 00:12

timmer


1 Answers

What about

do_work(false);
if (x_can_be_true)
    do_work(true);

This is equivalent to your simple example, but may not be a solution to what you're really trying to do.

like image 194
Kevin Avatar answered Apr 08 '23 07:04

Kevin