Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make std::optional constructor emit implicit conversion warnings

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?

like image 421
user6480075 Avatar asked Apr 11 '19 19:04

user6480075


1 Answers

List initialization prohibits narrowing conversions.

By the way, it looks like some compilers do warn on the issue: https://godbolt.org/z/P8Mv8v83d

like image 76
vines Avatar answered Nov 13 '22 10:11

vines