7

In C++11 I declare the following union:

union U4 {
    char c;
    int i;
    static int si;
};

When I compile this code with g++ 4.7.0 using -std=c++11 -pedantic-errors, I get the following errors (with minor editing):

error: local class ‘union U4’ shall not have static data member ‘int U4::si’ [-fpermissive]
error: ‘U4::si’ may not be static because it is a member of a union

The FDIS (N3242) does not explicitly allow static data members of named unions, as far as I can see. But I also don't see where the FDIS disallows static data members of named unions either The FDIS does repeatedly refer to what can be done with "non-static data members" [section 9.5 paragraph 1]. By contrast, that suggests the standard permits static data members of unions.

I don't have any use in mind for a static data member of a union. If I needed it I could probably get a close enough effect with a class containing an anonymous union. I'm just trying to understand the intent of the standard.

Thanks for the help.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
sschurr
  • 293
  • 1
  • 8
  • 2
    First of all, local class-types aren't allowed to have static data members in general (`§9.4.2/5`), so that's where your first error comes from. For static data member in a non-local `union` Clang compiles just fine. – Xeo Apr 14 '13 at 07:24

1 Answers1

5

Yes this is allowed. Section 9 of the Standard uses the word class for classes, structs and unions, unless it explicitly mentions so otherwise. The only restrictions on static union members are for local unions (9.4.2/5) and for anonymous unions (9.5/5).

#include <iostream>

union Test
{
    static int s;   
};

int Test::s;

int main()
{
   Test::s = 1;
   std::cout << Test::s;  
}

Output on LiveWorkSpace. Note that it compiles on Clang 3.2 but not on gcc 4.8.0 or Intel 13.0.1. It appears this is a gcc/Intel bug.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • sed s/Output on Ideone/Output on LiveWorkspace/g – niXman Apr 14 '13 at 09:26
  • @rhalbersma Wow. Nice answer. Thanks very much. As an extra benefit from this answer I learned that there are differences between local and non-local unions. Oh, and the reason a local union can't have a static member is that there's no way to declare the storage [palm slaps forehead]. Thanks again. – sschurr Apr 14 '13 at 16:09
  • @sschurr Glad to have been of help. – TemplateRex Apr 14 '13 at 16:14