I'm trying to write a dynamic array template in c++
I'm currently overloading the [] operators and I'd like to implement a different behavior based on which side of assignment they are used on.
#include <iostream>
...
template <class T>
T dynamic_array<T>::operator[](int idx) {
return this->array[idx];
}
template <class T>
T& dynamic_array<T>::operator[](int idx) {
return this->array[idx];
}
using namespace std;
int main() {
dynamic_array<int>* temp = new dynamic_array<int>();
// Uses the T& type since we are explicitly
// trying to modify the stored object
(*temp)[0] = 1;
// Uses the T type since nothing in the array
// should be modified outside the array
int& b = (*temp)[0];
// For instance...
b = 4;
cout<<(*temp)[0]; // Should still be 1
return 0;
}
I get compiler errors when trying to overload like this for obvious reasons.
Is there a proper way to do this?
My search so far has not been successful. Anything I've seen with overloaded [] operators seems to accept that the user can modify the stored item outside of the object.
I've implemented methods to use (instance(int i), update(int i, T obj)) but it would be nice to be able to use this class like a regular array.