DoeUS DoeUS - 2 months ago 23
C++ Question

Making own random number class compitible with uniform_int_distribution

I created a class which is implementing MersenneTwister algorithm to generate pseudo-random numbers. My question is how can I make my generator work with default std::uniform_int_distribution? Header of my class is given below:

class MersenneTwister
{
public:
void initialize(unsigned int seed);
unsigned int extract();

private:
unsigned int twist();
unsigned int _x[624];
signed int _index;
};

Answer

Modelling the UniformRandomBitGenerator concept should do it:

http://en.cppreference.com/w/cpp/concept/UniformRandomBitGenerator

Screenshot of the concept's requirements

Something like this:

#include <limits>

class MersenneTwister
{
public:
    void initialize(unsigned int seed);
    unsigned int extract();

    //
    // model the concept here
    //

    using result_type = unsigned int;
    static constexpr result_type min() { return std::numeric_limits<result_type>::min(); }
    static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }
    result_type operator()()
    {
        return extract();
    }

private:
    unsigned int twist();
    unsigned int _x[624];
    signed int _index;
};
Comments