Say I have a struct with a bunch of members:
struct foo {
int len;
bar *stuff;
};
As it so happens stuff
will point to an array of bar
s that is len
long. I'd like to encode this in stuff
's type. So something like:
struct foo {
int len;
DependentLength<bar, &foo::len> stuff;
};
Then I could implement DependentLength
to behave like a pointer to a bar array but that asserts when trying to looking at an index bigger than foo::len
. However, I can't implement DependentLength<&foo::len>::operator[]
because operator[] only takes one parameter, the index, and it needs to know the location of the 'foo' object in order to dereference the member pointer template parameter and do the assert check.
However, I happen to know that DependentLength will only ever be used here as a member of 'foo'. What I'd really like to do is tell DependentLength where to find len relative to itself, rather than relative to a foo pointer. So something like DependentLength<(char*)&foo::stuff - (char*)&foo::len> stuff;
, but that's not legal C++. Is there a good or failing that evil language hack that could make this work?