随机数模板——超越rand
无AI!
thread_local static mt19937 rnd(chrono::duration_cast<chrono::nanoseconds>
(chrono::system_clock::now().time_since_epoch()).count());
template<typename T>
T random(T L, T R){
static_assert(is_arithmetic_v<T>
, "Template parameter 'T' must be an arithmetic type.");
if constexpr (is_integral_v<T>){
#ifdef _DEBUG
if (L > R){
throw invalid_argument("For integral types,\
L must not exceed R.");
}
#endif
uniform_int_distribution<T> dist(L, R);
return dist(rnd);
}else if constexpr (is_floating_point_v<T>){
#ifdef _DEBUG
if (L >= R){
throw invalid_argument("For floating-point types,\
L must be strictly less than R.");
}
if (!isfinite(L) || !isfinite(R)){
throw invalid_argument("Bounds must be finite numbers.");
}
#endif
uniform_real_distribution<T> dist(L, R);
return dist(rnd);
}
}