我有一个结构体,它包含3个不同的数组,比如
struct MyArrys
{
int arr1[3];
int arr2[3];
int arr3[3];
}
我需要根据步长值获得一个指定的数组,例如考虑这个函数:
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;
}
步长值只有1、2、3,与数组数相似。
我试图实现一个名为getArrayValue
的函数,该函数将根据步骤
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;
}
这个方法有效。
有更好的方法吗?我可以在这里使用SFINAE吗?以及如何?甚至值得使用SFINAE吗?
可以使用指针指向成员的表。
的例子:
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];
}