Created
April 7, 2014 19:21
-
-
Save sundeepblue/10034600 to your computer and use it in GitHub Desktop.
create an array class with bounds checking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T, unsigned int N> | |
class SafeArray { | |
protected: | |
T a[N]; | |
public: | |
SafeArray() { | |
memset(a, 0, sizeof(a)); | |
} | |
int size() { return N; } | |
T& operator[] (unsigned int i) { | |
if(i >= N) // index out of range, return a null reference to provoke error | |
return *(T*)0; | |
return a[i]; | |
} | |
}; | |
int main() { | |
// usage of SafeArray | |
SafeArray<float, 100> list; | |
for(int i=0; i<list.size(); ++i) | |
cout << list[i] << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment