I am writing tests using the TYPED_TEST feature of google tests, which allows me to generalize a test to multiple types. I am testing a class template for the types int and double. In a test, I would need to generate random numbers. To do so, I have tried using the std::uniform_int_distribution<T> and the std::uniform_real_distribution<T> but have ran into static asserts.
As the names indicate, std::uniform_int_distribution<T> checks if T is an integral type and std::uniform_real_distribution<T> checks that T is a floating point type.
Since my test automatically tests for int and then for double, I have been trying to write some kind of function that would allow me to chose the right kind of distribution for the type at compile time. More precisely, something like:
template<class T> Distribution get_right_distribution(const T& a, const T& b) { if(T is integral) // Compile time is needed, runtime // fails since both if and else have to compile { return std::uniform_real_distribution(a, b); } else { return std::uniform_real_distribution(a, b); } } Note that this is only a pseudocode of what I have been trying to do. This kind of logical branch fails because the if AND the else have to compile.
I have done some research on how to do this and I feel like std::is_integral<T> and std::is_floating_point<T> are part of the solution, but I have not been able to compile anything so far. I mainly tried two things:
- Make a kind of compilation time by using template specialization.
- Use
enable_if.
Using the first approach I ended up with an error message telling me my overloads were ambiguous. Using the second approach, I tried some stuff but got lost in the abominable syntax (at least for someone not used to it) which it lead to.
Do you have a suggestion on how this could be accomplished?
P.S. I would like to see how this could be done, so splitting my test in two would not be an acceptable answer for me.