Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ template for generating parts of switch statement?

Is it possible to write a template

Foo<int n>

such that:

Foo<2>

gives

switch(x) {
  case 1: return 1; break;
  case 2: return 4; break;
}

while

Foo<3>

gives

switch(x) {
  case 1: return 1; break;
  case 2: return 4; break;
  case 3: return 9; break;
}

?

Thanks!

EDIT:

changed code above to return square, as many have guessed (and I poorly asked)

like image 570
anon Avatar asked Jan 23 '23 15:01

anon


1 Answers

Yes, make a template with an oversized master switch and hope/help the optimizer turns it into a little switch. See my answer to your other question Runtime typeswitch for typelists as a switch instead of a nested if's?. Also, don't duplicate-post.

like image 50
Potatoswatter Avatar answered Jan 30 '23 12:01

Potatoswatter