Skip to content

Commit

Permalink
Suppress -Wfloat-equal warning in implementation of gsl::narrow (#1043)
Browse files Browse the repository at this point in the history
In the implementation of gsl::narrow, there is a comparison `static_cast<U>(t) != u` which may be comparing two floats.
The comparison here is done purposefully to categorize ill effects of narrowing conversion, since the values being compared *should* be the same when compared with `operator==`. 
Note, using #pragma GCC will suppress this warning for both GCC and Clang.
  • Loading branch information
dmitrykobets-msft committed Apr 14, 2022
1 parent 3837236 commit 2bfd495
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
7 changes: 7 additions & 0 deletions include/gsl/narrow
Expand Up @@ -43,10 +43,17 @@ GSL_SUPPRESS(p.2) // NO-FORMAT: attribute // don't rely on undefined behavior
// and cannot fit into the destination integral type), the resultant behavior is benign on the platforms
// that we target (i.e., no hardware trap representations are hit).

#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#endif
if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{}))))
{
throw narrowing_error{};
}
#if defined(__clang__) || defined(__GNUC__)
#pragma GCC diagnostic pop
#endif

return t;
}
Expand Down
4 changes: 4 additions & 0 deletions tests/CMakeLists.txt
Expand Up @@ -89,6 +89,7 @@ if(MSVC) # MSVC or simulating MSVC
>
$<$<CXX_COMPILER_ID:Clang>:
-Weverything
-Wfloat-equal
-Wno-c++98-compat
-Wno-c++98-compat-pedantic
-Wno-covered-switch-default # GTest
Expand Down Expand Up @@ -122,6 +123,7 @@ else()
-Wpedantic
-Wshadow
-Wsign-conversion
-Wfloat-equal
-Wno-deprecated-declarations # Allow tests for [[deprecated]] elements
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>>:
-Weverything
Expand Down Expand Up @@ -227,6 +229,7 @@ if(MSVC) # MSVC or simulating MSVC
>
$<$<CXX_COMPILER_ID:Clang>:
-Weverything
-Wfloat-equal
-Wno-c++98-compat
-Wno-c++98-compat-pedantic
-Wno-missing-prototypes
Expand All @@ -250,6 +253,7 @@ else()
-Wpedantic
-Wshadow
-Wsign-conversion
-Wfloat-equal
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>>:
-Weverything
-Wno-c++98-compat
Expand Down
2 changes: 2 additions & 0 deletions tests/utils_tests.cpp
Expand Up @@ -149,5 +149,7 @@ TEST(utils_tests, narrow)
EXPECT_TRUE(
narrow<std::complex<float>>(std::complex<double>(4, 2)) == std::complex<float>(4, 2));
EXPECT_THROW(narrow<std::complex<float>>(std::complex<double>(4.2)), narrowing_error);

EXPECT_TRUE(narrow<int>(float(1)) == 1);
}
#endif // GSL_KERNEL_MODE

0 comments on commit 2bfd495

Please sign in to comment.