Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent implicit conversions from float to double in C++

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).

like image 709
user3768612 Avatar asked Jun 29 '14 18:06

user3768612


1 Answers

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.

like image 66
Rapptz Avatar answered Sep 20 '22 03:09

Rapptz