### Template type with rand()

Is there a way to generate random numbers with a Template type? I'm trying this but its not working.

 ``123456`` ``````template T random(T a, T b) { T temp = rand () % b; return temp; }``````
There would not be much value in this, as it would probably come down to a simple cast.

ie:

 ``12345`` ``````template< typename T> T random(T mx) { return static_cast(rand() % mx); }``````

But yeah... that's kind of a silly thing to do. And it still would only work with integral types.

Can you provide an example of how you'd use such a function?
> Is there a way to generate random numbers with a Template type?

C++11 pseudo random number generators and distributions are templates. Just use them.

 ``123456789101112131415161718192021222324252627282930313233343536`` ``````#include #include #include int main() { // std::mersenne_twister_engine<> is the random number engine // generates pseudo random numbers of an unsigned integral type // the integral type is a template parameter // mt19937 is a type alias, where the integral type is uint_fast32_t std::mt19937 rng( std::time(nullptr) ) ; // distributions use the random number generated by an engine // to generate an output that is mapped to a statistical pdf // these too are templates // uniform generates randon signed short values uniformly distributed in [ -100, +99 ] std::uniform_int_distribution uniform( -100, +99 ) ; // generate six such random numbers for( int i = 0 ; i < 6 ; ++i ) std::cout << uniform(rng) << ' ' ; std::cout << '\n' ; // poisson generates randon unsigned long values distributed according to // the discrete poisspo distribution with a mean of 12345.67 std::poisson_distribution poisson( 12345.67 ) ; // generate six such random numbers for( int i = 0 ; i < 6 ; ++i ) std::cout << poisson(rng) << ' ' ; std::cout << '\n' ; // normal generates randon float values distributed according to // the normal distribution with a mean of 10 and standard deviation of 3.5 std::normal_distribution normal( 10, 3.5 ) ; // generate six such random numbers for( int i = 0 ; i < 6 ; ++i ) std::cout << normal(rng) << ' ' ; std::cout << '\n' ; }``````
Topic archived. No new replies allowed.