mardi 8 janvier 2019

Template function which generate random value from min to max of every type

i need to write template of function which gets type eg. int, and then it generates random value from MIN_INT to MAX_INT

template<typename TYPE>
TYPE generateRandom()
{
    srand(static_cast<unsigned int>(time(nullptr)));
    TYPE generatedValue;
    //code :/
    return generatedValue;
}

few problems here:

  • rand generate to0 small value (RAND_MAX)
  • in rand i can't do INT_MAX+1 to include int max and negative values

I tried also something like this:

std::random_device randomDevice;
std::mt19937_64 generator(randomDevice());

if(std::numeric_limits<TYPE>::is_integer)
{
    std::uniform_int_distribution<TYPE> dice(std::numeric_limits<TYPE>::min(),std::numeric_limits<TYPE>::max());
    generatedValue=dice(generator);
}
else
{
    std::uniform_real_distribution<TYPE> dice(std::numeric_limits<TYPE>::min(),std::numeric_limits<TYPE>::max());
    generatedValue=dice(generator);
}

but it didnt work :/




Aucun commentaire:

Enregistrer un commentaire