jeudi 18 novembre 2021

Template function for random number generation (static assertion failed)

I created a simple template function to generate a random number of type T (I need int or float) in range [low, high) as follows:

template <typename T>
T randm(T low, T high)
{
    static std::random_device seeder;
    static std::mt19937 gen(seeder());
    std::uniform_real_distribution<T> dis(low, high);
    return dis(gen);
}

However when I try to call it as:

int r = randm<int>(0, 10);

I get the error: "static assertion failed: result_type must be a floating point type".

I found out that if I use uniform_real_distribution<> instead of uniform_real_distribution<T>, it works, but I am not sure why (and if I am not mistaken uniform_real_distribution<> defaults to double which I don't need).




Aucun commentaire:

Enregistrer un commentaire