Chciałbym zrobić wygodną funkcję do losowania dowolnego typu liczb. Bez konieczności deklarowania generatora pseudolosowego, maksymalnie wygodne.
#include <exception>
#include <iostream>
#include <random>
#include <type_traits>
template<typename T>
T random(T begin, T end)
{
static std::random_device rd;
static std::mt19937 gen(rd());
if (std::is_floating_point<T>::value)
{
std::uniform_real_distribution<T> dis(begin, end);
return dis(gen);
}
else if (std::is_integral<T>::value)
{
std::uniform_int_distribution<T> dis(begin, end);
return dis(gen);
}
else throw std::invalid_argument("Function 'random' must have a numeric arguments");
}
int main()
{
std::cout << std::fixed;
typedef float type;
type a = 0;
type b = 1;
for (size_t i = 0; i < 10; i++)
{
std::cout << random(a, b) << "\n";
}
std::cin.get();
}
Wszystko w miarę dobrze działało w momencie gdy nie przesyłałem typu jakiego chcę otrzymać:
std::uniform_real_distribution<> dis(begin, end);
std::uniform_int_distribution<> dis(begin, end);
Kod błędów:
error C2338: make_signed<T>/make_unsigned<T> require that T shall be a (possibly cv-qualified) integral type or enumeration but not a bool type.
error C2338: invalid template argument for uniform_int_distribution: N4606 26.6.1.1 [rand.req.genl]/1e requires one of short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long
Czy dałoby się to naprawić? Czy może droga, którą podążam jest zła i może mógłbym to zrobić w inny sposób?