使std :: optional构造函数发出隐式转换警告

use*_*075 8 c++ compiler-warnings implicit-conversion clang++

我正在尝试摆脱有损隐式转换的代码库,因此正在使用-Wconversionclang ++下的标记进行编译。以下代码预期会输出警告,但不会输出。

#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;
}
Run Code Online (Sandbox Code Playgroud)

make_optional生产线上,我size_t无声地缩小为a uint8_tuint8_t x2 = x;例如,如果我写,我得到了预期的缩小转换警告。

当我使用std::optional构造函数时,也会发生这种情况。在我给出的代码中,调用了make_optional重载2,该调用调用了可选的构造函数重载6。这构造了Optional,就好像直接初始化包含的值一样,并且直接初始化不会引发隐式变窄转换警告。

除了编写optional自己的不隐藏缩小转换的类之外,还有什么方法可以使上述代码引发缩小转换警告?

vin*_*nes 1

列表初始化禁止缩小转换范围。

顺便说一句,看起来有些编译器确实对这个问题发出了警告:https://godbolt.org/z/P8Mv8v83d