How to use operator()(Generator& g, const param_type& params); of std::uniform_int_distribution. This is my code
#include <iostream>
#include <random>
int get_random_int(const int lower_limit, const int upper_limit) {
std::random_device rd{};
std::mt19937 gen{rd()};
static std::uniform_int_distribution<> dist;
// use operator()(Generator& g, const param_type& params);
return dist(gen, lower_limit, upper_limit);
}
int main() {
std::cout << get_random_int(1, 1000000) << std::endl;
}
>Solution :
You need to create an object of type param_type.
return dist(gen, std::uniform_int_distribution<>::param_type{lower_limit, upper_limit});
You can shorten the name to decltype(dist)::param_type, though the syntax isn’t much more readable in my opinion. Name alias would also make it shorter and cleaner.
Implicit construction with just {lower_limit, upper_limit} doesn’t work: https://godbolt.org/z/4cr3f758K, although I don’t see a requirement in cppreference that would mandate explicit constructor.
Also, note that the expensive part of the operation is setting up random number engine (here std::mt19937), not the distribution itself. It would be better (and easier) to make that static instead:
int get_random_int(const int lower_limit, const int upper_limit) {
static std::random_device rd{};
static std::mt19937 gen{rd()};
return std::uniform_int_distribution{lower_limit, upper_limit}(gen);
}