C++11 中赋值列表和初始化列表之间缩小的差异

Differences in narrowing in C++11 between assignment and initialiser lists

C++11 给了我们初始化列表。我了解到这些不执行缩小转换,这有时会破坏现有代码的编译,例如在对具有隐式 int 加宽值的枚举值进行操作时:

   enum COMMAND
   {
     COMMAND_WRITE_MISC_CONFIG = 0x70
   };


   struct CommandSettings
   {
     quint8 buddy;
   };


   void NarrowingTest::testNarrowing()
   {
     quint8 i = 100;
     CommandSettings test{static_cast<quint8>(COMMAND_WRITE_MISC_CONFIG | i)};
     quint8 x = COMMAND_WRITE_MISC_CONFIG | i;
     QVERIFY(true);
   }      

如果没有转换,test 的初始化将无法编译。

我正在寻找的是 x 的赋值初始化背后的基本原理仍然有效。

CommandSettings test{static_cast<quint8>(COMMAND_WRITE_MISC_CONFIG | i)};

这是一个aggregate initialization

来自上面的参考:

The effects of aggregate initialization are:

...

If the initializer clause is an expression, implicit conversions are allowed as per copy-initialization, except if they are narrowing (as in list-initialization) (since C++11).


quint8 x = COMMAND_WRITE_MISC_CONFIG | i;

这是一个copy initialization

来自上面的参考:

The effects of copy initialization are:

...

Otherwise (if neither T nor the type of other are class types), standard conversions are used, if necessary, to convert the value of other to the cv-unqualified version of T.

至少为了向后兼容,它应该允许缩小转换。