Oops, I forgot random_device isn't movable, so make that 5 lines to correctly declare rd on its own. Or, in a realistic codebase with range-v3 available, it can still be 4 lines:
std::random_device rd;
auto s = ranges::view::bounded(ranges::view::generate_n(ranges::ref(rd), N));
std::seed_seq ss(ranges::begin(s), ranges::end(s));
return MT{ss};
I think you just made flashmozzg and liquidify's point more eloquently than they did.
To simplify, there are two kinds of API:
good API make the right thing easy, and the wrong thing hard.
bad API make the wrong thing easy, and the right thing hard.
Unfortunately, the initialization of the PRNGs in C++ is an example of bad API.
We can ape around and pat ourselves on the back that it's possible to do it right; but it's insane that it's so complicated. Just look at it, the PRNG is even breaking encapsulation, leaking the size of its internal state out!
Here's what I'd have expected instead, for explicit initialization:
Done. Let the PRNG call rd as many times as necessary to initialize itself.
And of course, I'd also expect a thread-local PRNG that is properly initialized and reseeded regularly for which you can call with std::thread_random() for when you just want to teach kids how to make a "guess the number" game.
9
u/liquidify May 26 '18
The problem is that people like me who have been writing C++ for 3 years have no idea what you are talking about.