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?
make_optional
is sensed to use deduction... else directly useoptional<T>
. – Sirloinoptional<uint8_t>{x}
fail as desired? – Matrona