jeudi 10 janvier 2019

How to fix "static assertion failed: template argument not an integral type" error?

I want to generate any number between 0 and max value of given type(T). There is no problem with generating numbers for int, short, long, etc, but i cannot do this for float and double. I get this error: "static assertion failed: template argument not an integral type".

My code:

#include <iostream>
#include <limits>
#include <random>

template<class T>
T questGenerator()
{
    std::random_device rd;
    std::default_random_engine generator(rd());
    std::uniform_int_distribution<T> distribution(0, std::numeric_limits<T>::max());

    return distribution(generator);
}

int main()
{
    std::cout << questGenerator<float>();
}

This is an input and output example that I was given:

input:

std::cout << generateQuest<short>() << std::endl;
std::cout << generateQuest<short>() << std::endl;
std::cout << (short)generateQuest<char>() << std::endl;
std::cout << (short)generateQuest<char>() << std::endl;
std::cout << generateQuest<float>() << std::endl;
std::cout << generateQuest<float>() << std::endl;

output:

10105
5332
52
110
3.39889e+38
2.7026e+38




Aucun commentaire:

Enregistrer un commentaire