Re: Array operator overloading from typedef?
On Apr 19, 10:06 pm, SG <s.gesem...@gmail.com> wrote:
On 20 Apr., 05:35, "Jeff M." <mass...@gmail.com> wrote:
I have a type that's - for all intensive purposes - a kind of variant.
We'll call this class Foo. There's nothing really special in it,
except that it ends with byte[0], and we always allocate more space
for the data that Foo manages.
struct Foo
{
// stuff
char byte[0];
};
Now, we always have a pointer to a Foo - never a reference or a static
allocation. And because Foo is actually hidden a bit, there's a
different type that is exposed to all the other code... let's call it
Thing:
typedef Foo* Thing;
Now, what I'd _like_ to do is overload the [] operator in such a way
that, given a Thing, I can index into Foo::byte and get what I need. I
can obviously put the [] operator inside of Foo, but then I end up
with a lot of code that looks like this:
Thing p = ... ;
doSomething((*p)[4]);
Which isn't exactly very readable. I've also toyed with making Thing
something other than a typedef and putting the [] operator inside of
that. In my side test app, that works, but there would be a lot of
code to change if I decided to go down that road; I'd rather not.
This is more of a C99 hack that isn't and won't be supported by C++
IIRC.
Given C++'s goal of being as compatible with C as reasonable, I would
expect C++ to sometime support this behavior, assuming it currently
doesn't. I think it does in part. In C++, you are allowed to access a
POD struct through a pointer to a different POD struct as long you
only access the common leading part (if any). As for declaring or
accessing that ending array, I don't know if it's formally supported,
but it should be supported by all implementations I imagine (possibly
have to change it to size 1 to get it to compile, but otherwise
supported.)
Also, you can't overload operator[] on pointers. You should write
your own class "Thing" or simply use a vector<char> instead which is
smart enough to manage its array and clean up on destruction.
Indeed. For example:
struct thing
{ foo * f;
char& operator[] (size_t x) { return f.byte[x]; }
};
And as SG said, do you really need such hacky code? If this is not a
performance critical application, consider the development and
maintenance costs which could be saved by using something like
std::vector.