Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++, bitfields and ADL

g++ fails to compile following code snippet:

namespace X {
  enum En {A, B};
  bool test(En e);
}

bool check() {
  union {
    struct {
      X::En y:16;
      X::En z:16; 
    } x;
    int z;
  } zz;
  return test(zz.x.y);
}

The error it gives is following

In function 'bool check()': 15 : error: 'test' was not declared in this scope return test(zz.x.y); ^ 15 : note: suggested alternative: 3 : note: 'X::test' bool test(En e); ^~~~ Compilation failed

If i make y a regular member, rather than a bitfield, code compiles successfully. Calling a name-spaced test works as well. Clang compiles the program as-is without any complains.

Putting bitfield business aside (I do not love it at all, but codebase has it) and not focusing on whether I have a guarantee of fitting an enum into the 16-bit member or not, is there something special regarding bitfields which prevents ADL from kicking in as I expect it?

like image 458
SergeyA Avatar asked Aug 01 '16 19:08

SergeyA


1 Answers

The underlying type of plain enums is implementation-defined:

C++03 standard 7.2/5

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int

The underlying time of struct bitfield enums is also implementation-defined:

C++03 standard 9.6/3

A bit-field shall have integral or enumeration type (3.9.1). It is implementation-defined whether a plain (neither explicitly signed nor unsigned) char, short, int or long bit-field is signed or unsigned.

So because the type of both X::En y:16 and X::En are implementation-defined, the implicit conversion between them is also implementation-defined, which I think explains the ADL difference that you're seeing across compilers.

like image 166
Giovanni Funchal Avatar answered Oct 05 '22 06:10

Giovanni Funchal