SunCC 5.12 到 5.14 和 "Types cannot be declared in anonymous union"

SunCC 5.12 through 5.14 and "Types cannot be declared in anonymous union"

我们在 SunCC 5.12 到 5.14 下遇到编译警告。其他编译器,如 Clang、GCC、ICC 和 MSVC 不会抱怨。我不确定诊断结果,因为我以前没有遇到过。

有问题的代码是针对 BigInteger class 的,后面是有问题的联合。 class 试图找到最大的机器字,可以容纳可以使用 umulx.

等硬件执行的进位加法和乘法运算
       class Dword
       {
         ...
         private:
320        union
321        {
322        #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
323          dword m_whole;
324        #endif
325          struct
326          {
327          #ifdef IS_LITTLE_ENDIAN
328            word low;
329            word high;
330          #else
331            word high;
332            word low;
333          #endif
334          } m_halfs;
335        };
336      };

这是警告:

[  3%] Building CXX object CMakeFiles/cryptopp-object.dir/integer.cpp.o
/opt/solarisstudio12.3/bin/CC -fPIC -native -m64 -template=no%extdef -o CMakeFiles/cryptopp-object.dir/integer.cpp.o
-c /export/home/jwalton/cryptopp/integer.cpp
CC: Warning: -xchip=native detection failed, falling back to -xchip=generic
"/export/home/jwalton/cryptopp/integer.cpp", line 335: Warning: Types cannot be declared in anonymous union.
1 Warning(s) detected.

根据 Microsoft 在 Anonymous Unions:

Simply omitting the class-name portion of the syntax does not make a union an anonymous union. For a union to qualify as an anonymous union, the declaration must not declare an object.

如果我理解正确,我们有一个匿名结构,因为没有人可以实例化从第 325 行开始的私有成员struct {...} m_halfs。然后,SunCC 抱怨匿名联合有成员struct {...} m_halfs。对吗?

如果 struct {...} m_halfs 是问题所在,那么我们如何以可移植的方式清除它?

如果这不是问题,那么 SunCC 在抱怨什么?


我必须小心这个问题是如何解决的。性能是重中之重,代码在关键路径上。此外,我们还支持当代编译器的 GCC 3 和 VC++ 6.0;和 C++03、C++11、C++14 和 C++17。

最后一个问题是,我们是否应该 "do nothing" 并在 Solaris 上使用它?

N4296(这是 C++ 17 标准的初稿)说:

A union of the form

      union { member-specification } ; 

is called an anonymous union; it defines an unnamed object of unnamed type. Each member-declaration in the member-specification of an anonymous union shall either define a non-static data member or be a static_assert-declaration. [ Note: Nested types, anonymous unions, and functions cannot be declared within an anonymous union. — end note]

这正是您所拥有的 - 您没有 class 名称或成员名称,因此不允许您为 m_halfs 发明新的结构类型。我建议将结构定义移出联合。

   class Dword
   {
     ...
     private:
        struct word_struct
        {
        #ifdef IS_LITTLE_ENDIAN
            word low;
            word high;
        #else
            word high;
            word low;
        #endif
       };
       union
       {
       #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
           dword m_whole;
       #endif
           word_struct m_halfs;
       };
   };

这不会对性能产生影响(但请注意,这种使用联合访问变量不同部分的技巧可能会违反严格的别名规则 - 这意味着您的程序可能具有未定义的行为。)