I am learning C++ and studying Chapter 18 of Vandevoorde and Josuttis's C++ Templates. I retyped their code for Expression Templates, but the following is producing the error
sarray1.cpp:36:6: error: ‘T& SArray<T>::operator[](size_t) const’ cannot be overloaded
T& operator[] (size_t idx) const {
^
sarray1.cpp:32:5: error: with ‘T SArray<T>::operator[](size_t) const’
T operator[] (size_t idx) const {
Here's the code:
template <typename T>
class SArray {
public:
...
T operator[] (size_t idx) const {
return storage[idx];
}
T& operator[] (size_t idx) const {
return storage[idx];
}
...
};
I am just learning C++ so I hadn't seen an instance of an overloaded function that differed only be return type, but I see that this is indeed done: Overload a C++ function according to the return value. I also see that []
is not on the list of operators that cannot be overloaded in C++. I can't think of what else could be going wrong. What is the reason for the above error?