I want to create a piece of code that use a type called Number
that may be a floating point number or any integer number (such uint64_t
). I have the variable dist
that is the distribution that should be used to generate random numbers, but it should be different in any of those cases, so i would like to do something like:
constexpr bool number_is_floating = std::is_floating_point<Number>::value;
#if number_is_floating
std::uniform_real_distribution<Number> dist(1.0, 1000.0);
#else
std::uniform_int_distribution<Number> dist(1, 1000);
#endif
But of course this is not going to work, because preprocessor variables get evaluated before the constant number_is_floating
does, so this expression will always be false. I actually tried to do this:
Number getran() {
if constexpr (number_is_floating)
return std::uniform_real_distribution<Number>(1.0, 1000.0)(eng);
else
return std::uniform_int_distribution<Number>(1, 1000)(eng);
}
But this is not working because we are trying to compile code that inits uniform_int_distribution
with a type that may or may not be integer (and the same for the real distribution).
What is the best and most-elegant way to make this code works even if Number
is or not floating point?
Aucun commentaire:
Enregistrer un commentaire