Re: How to cast from &BYTE to &My_Type ?
Am 20.09.2011 09:17, schrieb int21h:
I have a protocol that describes packages as sets of bytes. Some bytes
have several
information included, like struct Format below. I need to do something
like "Named Parameter Idiom". But I don't succeed in providing an
"accessor" that returns something different as&BYTE (original type).
How can I accomplish this (ctor with BYTE param, operator= didn't
work)?
Below is a small sample showing what I try to do. Appreciate your
help.
typedef unsigned char BYTE;
template<int SIZE>
struct Base {
BYTE data_[SIZE];
};
struct Format {
// Does not help: Format(const BYTE&) {}
BYTE layout : 3;
BYTE length : 5;
};
template<int SIZE>
struct Package : public Base<SIZE> {
static const int OFFSET_SOURCE = 1;
static const int OFFSET_TARGET = 2;
static const int OFFSET_FORMAT = 0;
// kind of " Named Parameter Idiom"
BYTE& source() { return data_[OFFSET_SOURCE]; }
BYTE& target() { return data_[OFFSET_TARGET]; }
Both the source() and the target() implementation should be ill-formed,
because Base is a dependent base class and there is no data_ member in
Package. You can use this->data_[whatever] instead of data_[whatever],
though. This will defer the resolution of the name 'data_' until
instantiation time.
// Next line won't compile: cannot convert from 'BYTE' to
// 'Format&'
// Don't want to use a reinterpret_cast either.
Format& format() { return data_[OFFSET_FORMAT]; }
};
This approach cannot work, because bit-fields are no addressable units.
If it is important to you, that there exists a single memory area (The
array member data_), I suggest that you use normal bit-masking
techniques to get and set the corresponding bit ranges within
data_[OFFSET_FORMAT] that refer to layout and length of the format
(Otherwise you could have a member Format and a member data_[SIZE-1]).
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]