Basically, if I want something like this,
double b = sin(2.2);
but accidentally write something like this,
double b = sin(2.2f);
there is no error or even warning message, even though this clearly leads to a different, inaccurate, and therefore incorrect result. This type of error could be prevented, by forcing the compiler to not do any implicit conversions of float to double. Is there any way to achieve this, be it through a compilation switch (preferably in Visual Studio), some smart macros, or a class which behaves like float/double variables and declares its own operators?
Edit: I am also interested in solving similar problems using operators (such as e.g. double b = 2.2f*2.2f), or assignments (double b=2.2f).
You can use a type_assert
utility.
Example:
#include <cmath>
#include <type_traits>
template<typename T, typename U>
const U& type_assert(const U& u) {
static_assert(std::is_same<T, U>::value, "...");
return u;
}
int main() {
double t = type_assert<double>(std::sin(2.2f));
}
If the expected type is different then it'll give you a compiler error. Chances are the compiler could probably optimise this if it passes though, at least it did in my case with -O3
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With