Last active
November 21, 2018 21:30
-
-
Save jotux/132a93a4bcd99def0356baa03210cce4 to your computer and use it in GitHub Desktop.
C++ array access with automatic dirty flag set.
This file contains hidden or 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
#include <iostream> | |
#include <stdio.h> | |
#include <string.h> | |
using namespace std; | |
template<int N> | |
class X | |
{ | |
private: | |
int data[N]; | |
class Proxy | |
{ | |
private: | |
X<N>& parent; | |
int index; | |
public: | |
Proxy(X<N>& p, int x) : parent(p), index(x){} | |
void operator=(int i) | |
{ | |
if (i != parent.data[index]) | |
{ | |
parent.dirty = true; | |
} | |
parent.data[index] = i; | |
} | |
operator int const &() | |
{ | |
return parent.data[index]; | |
} | |
int operator++(int) | |
{ | |
parent.data[index]++; | |
parent.dirty = true; | |
return parent.data[index]; | |
} | |
}; | |
public: | |
bool dirty; | |
X<N>() | |
{ | |
memset(data,0,N*sizeof(int)); | |
dirty = false; | |
} | |
Proxy operator[](int index) | |
{ | |
return Proxy(*this,index); | |
} | |
}; | |
int main() | |
{ | |
X<3> sample; | |
for (int i = 0;i < 3;i++) | |
{ | |
printf("%d %d\n",(int)sample[i],sample.dirty); | |
} | |
sample[1] = 0; | |
for (int i = 0;i < 3;i++) | |
{ | |
printf("%d %d\n",(int)sample[i],sample.dirty); | |
} | |
sample[1]++; | |
for (int i = 0;i < 3;i++) | |
{ | |
printf("%d %d\n",(int)sample[i],sample.dirty); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment