views:

532

answers:

2

Can I define in C++ an array operator that takes multiple arguments? I tried it like this:

const T& operator[](const int i, const int j, const int k) const{ 
 return m_cells[k*m_resSqr+j*m_res+i];
}

T& operator[](const int i, const int j, const int k){ 
 return m_cells[k*m_resSqr+j*m_res+i];  
}

But I'm getting this error:

error C2804 binary operator '[' has too many parameters
+10  A: 

Nope, you can't overload operator[] to accept multiple arguments. You instead can overload operator(). See [13.10] How do I create a subscript operator for a Matrix class? from the comp.lang.c++ FAQ.

jamesdlin
+4  A: 

You can do it with proxy pattern.

In two words: a[x][y], the first expression (a[x]) would return a different type, named proxy type, which would have another operator[]. It would call something like _storedReferenceToOriginalObject->At(x,y) of the original class.

You will not be able to do a[x,y], but I guess you wanted to overload the usual C++-style 2D array syntax anyway.

Pavel Radzivilovsky
This doesn't do what the user was asking about - he wanted a[x,y]
anon
@Neil Butterworth: I think there's an implicit "you can't do it, but here's an alternative" contained in the answer.
Jason
I think he wanted the C 2D-array syntax a[x][y] that would pass parameters to operator[](x,y), no? That would actually make sense.
Pavel Radzivilovsky
The comp.lang.c++ FAQ addresses this too:http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.11
jamesdlin