Ideally you should just be using bool types rather than "bit packing" into a single int.WilliamK wrote:Now, please, help me out here. I was wondering on the FLAG system. Right now I use a single int32 variable for the flag. And the bitOperation to check, set, clear flags. BUT, I'm wondering on using a structure for this instead, but I wonder if this is safe. Here's an example:
So, if I declare the Flag flag instead of int32 flag, is this safe to go from the Dynamic Library to the Host and back? I have no clue on this. I will test, it should be safe, since the structure is carefully declared, so I guess it is safe. I will run some tests tomorrow...Code: Select all
struct Flag { Flag() { flag = 0; }; inline void set(const int32 flagEnum) { flag |= bitToMask(flagEnum); }; static inline uint32 bitToMask(const int32 flagEnum) { return (uint32) 1 << (flagEnum & 31); }; int32 flag; };
Thanks again!
Alternatively it is possible to pack bits using a template like stl::bitset, although the real question is what is the point? Is it a memory issue? Why not leave the flags "unpacked" in a structure and pass a const reference to that structure?
http://cplus.about.com/od/learningc/ss/lowlevel_10.htm
Code: Select all
struct flag
{
bool flag1;
bool flag2;
bool flag2;
};
function(const flag &f);
Code: Select all
struct keystate
{
keystate() { clear(); }
void clear() { control = shift = alternate = left = middle = right = dbl = false; }
bool control;
bool shift;
bool alternate;
bool left;
bool middle;
bool right;
bool dbl;
};
If that still causes problems you can use a template:
Code: Select all
template <class T>
struct bool_t
{
bool operator =(const bool &b) {
return (data = b ? 1 : 0) != 0;
}
bool operator ==(const bool &b) const {
return (data != 0) == b;
}
bool operator !=(const bool &b) const {
return (data != 0) != b;
}
operator bool() const {
return data != 0;
}
T data;
};
typedef bool_t<int8_t> i8bool;
Keep in mind that if you use a struct for thus purpose (POD type) you must not mix types of different size or the padding of the struct will no longer be 1.
I don't find it is a problem in my own code even between platforms although if I were writing a filetype or interface I would use the template to ensure I know the size of the type.
