Overloaded operator & device memory

Hi,

In a metal shader I have a user-defined struct with a square brackets operator. This is a simplified version of it:

struct MyData
{
	float data[12];
	
	float operator[](int i) const
	{
		return data[i];
	}
};

I pass a device buffer of that type in a compute kernel function:

device const MyData* myDataBuffer

Using the operator with a thread-space object works fine:

MyData data_object = myDataBuffer[0];
float x = data_object[0];	// ok

..but trying to use it with the device-space buffer fails:

float x = myDataBuffer[0][0]; // compilation error
No viable overloaded operator[] for type 'const device MyData'
Candidate function not viable: address space mismatch in 'this' argument ('const device MyData'), parameter type must be 'const MyData'

For other operators I could define the function outside the struct and pass a reference to a device-memory object but the function for the square brackets operator can only be a member function.

Am I missing something that could make the above statement compile?

Answered by Graphics and Games Engineer in 773943022

You'll need to qualify the this pointer using the following syntax:

  float operator[](int i) device const {
    return data[i];
  }

You'll need to do this for any address space you expect to use your struct for.

Accepted Answer

You'll need to qualify the this pointer using the following syntax:

  float operator[](int i) device const {
    return data[i];
  }

You'll need to do this for any address space you expect to use your struct for.

That fixes the error, thanks.

Overloaded operator & device memory
 
 
Q