The C++11 std library has several random number generators (RNG), each implementing the concept UniformRandomNumberGenerator. These can then be used as argument for random distributions, see also this documentation for an overview.
The advantage of this design is that the choice of the underlying RNG engine is de-coupled from its application. However, the design also requires the definition (not merely the declarations) of all calls to the RNG to be available (if the RNG type is to remain unspecified as template parameter). Thus, in
struct complicated_random_distribution
{
/*
some data and auxiliary methods here
*/
// complicated; may call RNG::operator() many times
template<typename RNG>
some_type operator()(RNG&gen) const;
};
the member operator()
cannot be straightforwardly implemented in a separate compilation unit (CU), but must be available in the same header file (or one #include
d from it).
For a separate implementation, one ideally would want some way to pack a RNG in the same way as std::function<>
packs any callable object.
(Simply using std::function
and providing the values for RNG::min()
and RNG::max()
as arguments to a function defined in a separate CU is restrictive and will not allow to use, say, std::uniform_real_distribution<>
inside).
How can this be done? Are implementations for this available? Will the std library provide this in the future? Or am I after a red herring?
Edit Random number generators are required to have static
members min()
and max()
, making type-erasure hard or impossible (GNU's libstdc++ doesn't make this assumption and a type erasure with non-static members min()
and max()
works, but not with LLVM's libc++, which uses the standard required static
members). Is there a way to still solve this problem? If not, doesn't this imply that the C++ standard has a botched interface for random number generators?
Adapt the RNG with an
independent_bits_engine
, and type erase the adapted RNG. You have full knowledge of what theindependent_bits_engine
'smin()
andmax()
are.Here's a sketch:
This works in clang and gcc (with libstdc++), but this is not strictly a
UniformRandomNumberGenerator
, for the noted reason thatmin
andmax
are not static.GCC: http://rextester.com/ANAP79935
clang http://rextester.com/YCIIR21607