Implicit conversion to array index type

Viewed 83

Let's say I have following type:

struct XY
{
  short nIndex;
  
  constexpr operator int()
  {
     return nIndex;
  }
};

What can I change to make the following work:

char arr[10][255];

constexpr XY xy{1};

char *x = arr[xy];

I thought that just giving XY a convert-to-int operator would be enough but I'm getting the error:

no match for 'operator[]' (operand types are 'const char [10][255]' and 'const XY')

1 Answers

Since the variable is constexpr, you cannot call the conversion operator that is not const-qualified. Solution is simple: Make the conversion operator const qualified:

constexpr operator int() const
Related