Home > Enterprise >  Do the same operation on different variables based on the variant?
Do the same operation on different variables based on the variant?

Time:02-02

I need to same operation on an array of struct based on the variant. In compile time I know which array of struct should be updated using one generic function. Is inheritence is good, like I have 4 variants and 4 derived classes, every class sets a variable and the function updates corresponding array?

Or no inheritance and assign the right array in compile time?

Variant 1
Function has to update array1
Variant 2
Function has to update array2
…
…
array4

I tried to assign like

#ifdefined variant 1
typedef array array1
//array =array1;
#elifdefined variant 2
typedef array array2

This was not accepted.

CodePudding user response:

As you know the type in compile time, you can use if constexpr and std::is_same in the function that updates the values.

typedef std::vector<bool> Array1;
typedef std::vector<int> Array2;

#define VARIANT 1
#if VARIANT==1
  typedef Array1 Array;
#elif VARIANT==2
  typedef Array2 Array;
#else
  #error No suitable variant
#endif

void update(Array& parameter)
{
    if constexpr (std::is_same_v<Array, Array1>) {
        // Do something for Array1
    }
    else if constexpr (std::is_same_v<Array, Array2>) {
        // Do something for Array2
    }
    else {
        // No suitable type, #error should detect this
    }   
}

CodePudding user response:

i did it simply like this :)
#include <iostream>

using namespace std;

int variant=1; //for test - in actual this comes from template

struct mystruct
{
   int member1;
   int member2;
};

struct mystruct array1[4];
struct mystruct array2[4];

int main() {

  mystruct* array;

  //few test calues
  //fillup arrays for test 
  switch(variant)
  { 
      case 1:
      array = array1;
      break;
  
      case 2:
      array= array2;
      break;
  
      case3: //reserved
      break;
  
      default:
      break; 
   };

  for (int i = 0; i < 3; i  ) {
    cout << array[i].member1 << "\n";
    cout << array[i].member2 << "\n";
  }
  return 0;

}

  •  Tags:  
  • c
  • Related