Home > Mobile >  Get a specified array value from struct according to a function parameter value
Get a specified array value from struct according to a function parameter value

Time:12-06

I have a struct that holds 3 different arrays like this for example

struct MyArrys
{
int arr1[3];
int arr2[3];
int arr3[3];
}

I need to get a specified array according to a step value for example consider this function:

int doSomething(int x,int y, MyArrs arrs, const int step, const int idx)
{
  int z = // get arr1, arr2, or arr3
  return x y z;
}

The step values are only 1,2 and 3 similar to the number of arrays.

I've tried to implement a function called getArrayValue which will return the corresponding array value according to the step

int getArrayValue(const MyArrs& arrs, const int idx, const int step)
{
   switch(step)
   {
      case 0:
         return arrs.arr1[idx];
      case 1:
         return arrs.arr2[idx];
      case 2:
         return arrs.arr3[idx];
   }
} 

int doSomething(int x,int y, MyArrs arrs, const int step, const int idx)
{
  int z = getArrayValue(arrs,idx,step);
  return x y z;
}

This way works.

Is there a better way to do it? Could I use the SFINAE here? and how? Does it even worth using SFINAE?

CodePudding user response:

You can use a table of pointer-to-member.

Example:

int getArrayValue(const MyArrays& arrs, const int idx, const int step)
{
    using AnArray = int (MyArrays::*)[3];
    static const AnArray arrays[] = {&MyArrays::arr1, &MyArrays::arr2, &MyArrays::arr3};
    return (arrs.*arrays[step])[idx];
} 

  •  Tags:  
  • c
  • Related