C ++ template for generating parts of a switch statement?

Can I write a template

Foo<int n>

such that:

Foo<2>

gives

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

and

Foo<3>

gives

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

?

Thank!

EDIT:

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

+3
source share
5 answers

Yes, create a template with a large master switchand hope / help the optimizer turn it into a little switch. See My answer to your other Runtime typeswitch question for type lists as a switch instead of nested if? . Also, do not duplicate the message.

+5
source

switch, , ( x) . , , .

, , :

#include <cstdlib>
#include <iostream>
using namespace std;

template<int V> struct intswitch
{
    operator int() const
    {
        return V * V;
    }
};

int main() {

    cout << "1 = " << intswitch<1>() << endl
        << "2 = " << intswitch<2>() << endl
        << "3 = " << intswitch<3>() << endl
        << "4 = " << intswitch<4>() << endl
        << "5 = " << intswitch<5>() << endl
        << "6 = " << intswitch<6>() << endl
        << "7 = " << intswitch<7>() << endl
        << "8 = " << intswitch<8>() << endl
        << "9 = " << intswitch<9>() << endl
        << "10 = " << intswitch<10>() << endl
        ;
}

:

1 = 1
2 = 4
3 = 9
4 = 16
5 = 25
6 = 36
7 = 49
8 = 64
9 = 81
10 = 100
+2

, -, . - , , .

, , foo<N> 1 N, . , :

template <int t>
int foo(int x)
{
    return (x > t)   ? -1 :
           (x == t)  ? (x * x) :
                       foo<t -1>(x);
}    

template <>
int foo<0>(int x)
{
    return -1;
}
+2

No, you will need a lookup table for something like this helper.

0
source

I do not believe that you are actually looking for patterns here, but rather macros. Try this link for information on a C preprocessor that can do what you want. Templates work on types and are not suitable for what you are trying to do.

0
source

Source: https://habr.com/ru/post/1730445/


All Articles