How to switch between local and global settings for the initial state of C ++ 11 RNG?

In the code below, I would like to implement a flag (or something as simple) that has the same effect as commenting on local parameters and using global settings several times (in this example, two different numbers are given) and using local setting in another time (in this example, two identical numbers are given).

I tried the obvious "if" and "switch" structures without success.

#include <iostream> #include <random> void print(); std::seed_seq seed{1, 2, 3, 4, 5}; std::mt19937 rng(seed); // *global* initial state std::uniform_real_distribution<> rand01(0, 1); int main() { print(); print(); return 0; } void print() { std::mt19937 rng(seed); // *local* initial state std::cout << rand01(rng) << std::endl; } 
+5
source share
1 answer

Use the triple link and link:

 std::mt19937& ref = flag ? rng : local; 

Here flag is a validation condition, rng is a "global" random object, and local is more localized.

Linking the result reference to a triple is syntactically correct: you cannot do this with an if or similar, since these are not expressions of the correct type.

From this point, use ref . This will be valid as long as rng and local remain in scope.

+5
source

All Articles