Template type with rand()

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

1
2
3
4
5
6
template<typename T>
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:

1
2
3
4
5
template< typename T>
T random(T mx)
{
  return static_cast<T>(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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <random>
#include <iostream>
#include <ctime>

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<short> 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<unsigned long> 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<float> 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.