我想要一个模板化的类,它在下限和上限之间生成随机数(两个限制都可以是负数)。这是我到目前为止所拥有的:
template <typename T>
T RandomGenerator<T>::generate(T lowerLimit, T upperLimit)
{
static bool initialized = initialize();
return double(rand()) * (upperLimit - lowerLimit) / RAND_MAX + lowerLimit;
}
template <typename T>
bool RandomGenerator<T>::initialize()
{
srand(time(NULL));
}
int iVal = RandomGenerator<int>::generate(1, 10); //Generate integers between (and including) 1 and 10.
double dVal = RandomGenerator<double>::generate(-1, 1); //Generate doubles between (and including) -1 and 1.
这会正确生成双精度值,但整数是关闭的。有谁知道如何为整数和双精度编写通用解决方案?我不想要整数和双精度的不同功能。