The above code will always guarantee that your array will hold 2 "short int"s and 1 "char". As for adding data into that array, you'd have to interpret an address within the array as a specific type then write to that address. For example:
1 2 3 4 5 6 7 8 9 10
union MultiPointer
{
short *Short_;
char *Byte_;
};
MultiPointer Pointer_;
Pointer_.Byte_ = head;
*Pointer_.Short_ = short( 1 );
*( Pointer_.Byte_ + sizeof( short ) ) = 'W';
@cire: Please, tell me, what is not an abuse of "union"? </sarcasm > Also, you're code is good... if you like unnecessary complexity of a simple problem. Besides, the OP clearly stated that he/she will be using "short" and "char" as the target types; there's not need to bring templates into this.
One might start with uses that aren't using undefined behavior to avoid a simple cast. </sarcasm>
Also, you're code is good... if you like unnecessary complexity of a simple problem.Besides, the OP clearly stated that he/she will be using "short" and "char" as the target types; there's not need to bring templates into this.
I know right. Who would design code for a general case instead of a specific case? I mean, it's pretty well known that code should never be reused and requirements never change.
It's my experience that customers go to great lengths to help with this by ensuring they never actually provide any requirements in the first place. It they don't exist, they can't change :)
That's a good point. I had in mind integral types and bit shifting in the original code, but that wouldn't work with arbitrary types, and I kind of threw that code out there. A correct implementation would have store and retrieve functions that looked more like: