Skip to content

Commit 2bfd495

Browse files
Suppress -Wfloat-equal warning in implementation of gsl::narrow (microsoft#1043)
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.
1 parent 3837236 commit 2bfd495

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

include/gsl/narrow

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,17 @@ GSL_SUPPRESS(p.2) // NO-FORMAT: attribute // don't rely on undefined behavior
4343
// and cannot fit into the destination integral type), the resultant behavior is benign on the platforms
4444
// that we target (i.e., no hardware trap representations are hit).
4545

46+
#if defined(__clang__) || defined(__GNUC__)
47+
#pragma GCC diagnostic push
48+
#pragma GCC diagnostic ignored "-Wfloat-equal"
49+
#endif
4650
if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{}))))
4751
{
4852
throw narrowing_error{};
4953
}
54+
#if defined(__clang__) || defined(__GNUC__)
55+
#pragma GCC diagnostic pop
56+
#endif
5057

5158
return t;
5259
}

tests/CMakeLists.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ if(MSVC) # MSVC or simulating MSVC
8989
>
9090
$<$<CXX_COMPILER_ID:Clang>:
9191
-Weverything
92+
-Wfloat-equal
9293
-Wno-c++98-compat
9394
-Wno-c++98-compat-pedantic
9495
-Wno-covered-switch-default # GTest
@@ -122,6 +123,7 @@ else()
122123
-Wpedantic
123124
-Wshadow
124125
-Wsign-conversion
126+
-Wfloat-equal
125127
-Wno-deprecated-declarations # Allow tests for [[deprecated]] elements
126128
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>>:
127129
-Weverything
@@ -227,6 +229,7 @@ if(MSVC) # MSVC or simulating MSVC
227229
>
228230
$<$<CXX_COMPILER_ID:Clang>:
229231
-Weverything
232+
-Wfloat-equal
230233
-Wno-c++98-compat
231234
-Wno-c++98-compat-pedantic
232235
-Wno-missing-prototypes
@@ -250,6 +253,7 @@ else()
250253
-Wpedantic
251254
-Wshadow
252255
-Wsign-conversion
256+
-Wfloat-equal
253257
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>>:
254258
-Weverything
255259
-Wno-c++98-compat

tests/utils_tests.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,5 +149,7 @@ TEST(utils_tests, narrow)
149149
EXPECT_TRUE(
150150
narrow<std::complex<float>>(std::complex<double>(4, 2)) == std::complex<float>(4, 2));
151151
EXPECT_THROW(narrow<std::complex<float>>(std::complex<double>(4.2)), narrowing_error);
152+
153+
EXPECT_TRUE(narrow<int>(float(1)) == 1);
152154
}
153155
#endif // GSL_KERNEL_MODE

0 commit comments

Comments
 (0)