Oleksa
Oleksa

Reputation: 675

Autogenerate cases for a switch. Or another suggestion

Is there any way to autogenerate cases if necessary (with certain logic described by example) for a switch? Or maybe you have another suggestion. some code is always the same.

    int num = 0; // Global variable
    .
    .
    . 
    switch (num)
    {
    case 0:
    {
        //some code
        num++;
        break;
    }
    case 1:
    {
        if (CHECK(1)) // CHECK is macros for comparing 
        {
            //some code
            num++;
        }
        break;
    }
    case 2:
    {
        if (CHECK(1) && CHECK(2))
        {
            //some code
            num++;
        }
        break;
    }
    case 3:
    {
        if (CHECK(1) && CHECK(2) && CHECK(3))
        {
            //some code
            num++;
        }
        break;
    }
    case 4 ...

... and so on

Upvotes: 0

Views: 88

Answers (3)

Dmytro Dadyka
Dmytro Dadyka

Reputation: 2260

I have proposed using templates in this case.

template <int level>
bool check()
{
   return CHECK(level) && check<level - 1>();
}

template <>
bool check<0>() { return true;}

template <int level>
void caseCheck(int& num)
{
   if (num == level)
   {
      if (check<level>())
      // some code
      num++;
   }
   else
      caseCheck<level - 1>(num);
}

template <>
void caseCheck<0>(int& num)
{
   // some code
   num++;
}


caseCheck<NUM_CASES>(num);

Upvotes: 0

Quentin
Quentin

Reputation: 63144

Unless you're doing something fishy inside CHECK, it should be as easy as a for loop:

for(int i = 1; i <= num; ++i)
    if(!CHECK(i))
        return;

// some code
++num;

Upvotes: 1

Jesper Juhl
Jesper Juhl

Reputation: 31472

Sure. You can generate whatever code you need, stick it in a file, and then #include the generated file wherever needed in your source file.

Doing that can sometimes be a good idea and sometimes a horrible idea. It all depends on your code/problem/circumstances.

Upvotes: 0

Related Questions