D
Dave Rahardja
I have the following program that uses an array of chars to simulate a bit
set:
---------
// An out-of-bounds exception
class BoundsException {};
template <int bits = 1>
class Bitset
{
public:
Bitset()
{
// Clear all the bits in the bit flag bytes
for (int i = 0; i < charCount; ++i) {
bitFlags = 0;
}
}
// Sets a bit in the bitset.
void set(int bit)
{
if (bit >= bits || bit < 0) {
throw BoundsException();
}
int byteNum = bit / 8;
int bitNum = bit % 8;
bitFlags[byteNum] |= (1 << bitNum);
}
private:
static const int charCount = (bits + 7) / 8;
unsigned char bitFlags[charCount];
};
int main()
{
Bitset<9> bitset9;
bitset9.set(0); // OK
bitset9.set(-1); // BoundsException thrown
bitset9.set(8); // OK
bitset9.set(9); // BoundsException thrown
return 0;
}
---------
As you can see, I'm using runtime checks to bounds-check the bit number each
time set() is called.
However, it turns out that set() will only receive compile-time constants, and
never runtime computed values.
Is there a way to perform _compile-time_ bounds checking for the indexes? A
little template trickery maybe?
-dr
set:
---------
// An out-of-bounds exception
class BoundsException {};
template <int bits = 1>
class Bitset
{
public:
Bitset()
{
// Clear all the bits in the bit flag bytes
for (int i = 0; i < charCount; ++i) {
bitFlags = 0;
}
}
// Sets a bit in the bitset.
void set(int bit)
{
if (bit >= bits || bit < 0) {
throw BoundsException();
}
int byteNum = bit / 8;
int bitNum = bit % 8;
bitFlags[byteNum] |= (1 << bitNum);
}
private:
static const int charCount = (bits + 7) / 8;
unsigned char bitFlags[charCount];
};
int main()
{
Bitset<9> bitset9;
bitset9.set(0); // OK
bitset9.set(-1); // BoundsException thrown
bitset9.set(8); // OK
bitset9.set(9); // BoundsException thrown
return 0;
}
---------
As you can see, I'm using runtime checks to bounds-check the bit number each
time set() is called.
However, it turns out that set() will only receive compile-time constants, and
never runtime computed values.
Is there a way to perform _compile-time_ bounds checking for the indexes? A
little template trickery maybe?
-dr