Do they all inherit from a base class? Do I have to use templates?
(I am referring to these http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15319/)
They don't all inherit from a base (which is a little surprising), but it doesn't matter because that's not how C++ functors work.
For arbitrary RNGs of a single given type, you got it right as (now) posted.
If you mean, how do I define a function which accepts any random number generator as an argument.
template< class RNG > // RNG may be a functor object of any type
int random_even_number( RNG &gen ) {
return (int) gen() * 2;
}
You don't need to use any more templates than this, because of type deduction.
Defining one function to accept different RNG's is trickier because semantically that requires having a common base type. You need to define a base type.
struct RNGbase {
virtual int operator() = 0;
virtual ~RGNBase() {};
};
template< class RNG >
struct SmartRNG : RNGBase {
RNG gen;
virtual int operator() {
return gen();
}
};
int random_even_number( RNGBase &gen ) { // no template
return (int) gen() * 2; // virtual dispatch
}