I'm trying to rid my codebase of lossy implicit conversions, so I'm compiling with the -Wconversion
flag under clang++. The following code is expected to output a warning, but does not.
#include <cstddef>
#include <iostream>
#include <limits>
#include <optional>
int main() {
size_t x = std::numeric_limits<size_t>::max();
std::cout << x << std::endl;
auto x2 = std::make_optional<uint8_t>(x);
std::cout << (int)*x2 << std::endl;
return 0;
}
On the make_optional
line, my size_t
is silently narrowed to a uint8_t
. If instead I write uint8_t x2 = x;
for example, I get the expected narrowing conversion warning.
This also happens when I use the std::optional
constructor. In the code I gave, make_optional overload 2 is called which calls optional constructor overload 6. This constructs the optional as if direct-initializing the contained value, and direct initialization does not raise an implicit narrowing conversion warning.
Other than writing an optional
class of my own that does not hide narrowing conversions, is there any way to cause the above code to raise a narrowing conversion warning?
List initialization prohibits narrowing conversions.
By the way, it looks like some compilers do warn on the issue: https://godbolt.org/z/P8Mv8v83d
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