M
mike3
Hi.
I was reworking this program I had done in C++ and I came across this
little number:
---
template<class T>
class RandomGeneratorRanged : public RandomGeneratorRangedBase<T> {
protected:
T minVal, maxVal;
public:
RandomGeneratorRanged() : minVal(0), maxVal(1) {}
RandomGeneratorRanged(const T minVal_, const T maxVal_)
: minVal(minVal_), maxVal(maxVal_)
{
if(minVal > maxVal)
std::swap(minVal, maxVal);
if((static_cast<long>(minVal_) < c_rangeMin) ||
(static_cast<long>(maxVal_) > c_rangeMax))
// This is where the problem is
throw XXXXXException(ERROR_RANDOM_RANGE_OUT_OF_RANGE);
}
....
};
---
The class is supposed to wrap a random number generator and allow you
to set up a variable that can output random numbers in a preset range
(set up on construction). The T can be one of various integer types,
and that's where we run into problems. Namely, I've only ever used
this with signed types, but I wasn't sure how to make it go with
unsigned, because the "max check" there has c_RangeMin which is a
_negative_ (signed!!!!) number. So if you tried a
"RandomGeneratorRanged<unsigned int> foo(<smth>, <smth>)" _you'd get
into trouble_ and I realized I better do something about this before
it bites me in the ass. Is there a superior way to achieve this, that
will allow for both signed and unsigned use? As making classes for
each signed and unsigned integer type sounds like a way to make a mess
with duplicated code. Hence why there's a template there anyway.
I was reworking this program I had done in C++ and I came across this
little number:
---
template<class T>
class RandomGeneratorRanged : public RandomGeneratorRangedBase<T> {
protected:
T minVal, maxVal;
public:
RandomGeneratorRanged() : minVal(0), maxVal(1) {}
RandomGeneratorRanged(const T minVal_, const T maxVal_)
: minVal(minVal_), maxVal(maxVal_)
{
if(minVal > maxVal)
std::swap(minVal, maxVal);
if((static_cast<long>(minVal_) < c_rangeMin) ||
(static_cast<long>(maxVal_) > c_rangeMax))
// This is where the problem is
throw XXXXXException(ERROR_RANDOM_RANGE_OUT_OF_RANGE);
}
....
};
---
The class is supposed to wrap a random number generator and allow you
to set up a variable that can output random numbers in a preset range
(set up on construction). The T can be one of various integer types,
and that's where we run into problems. Namely, I've only ever used
this with signed types, but I wasn't sure how to make it go with
unsigned, because the "max check" there has c_RangeMin which is a
_negative_ (signed!!!!) number. So if you tried a
"RandomGeneratorRanged<unsigned int> foo(<smth>, <smth>)" _you'd get
into trouble_ and I realized I better do something about this before
it bites me in the ass. Is there a superior way to achieve this, that
will allow for both signed and unsigned use? As making classes for
each signed and unsigned integer type sounds like a way to make a mess
with duplicated code. Hence why there's a template there anyway.