Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all C++ compilers allow using a static const int class member variable as an array bound?

In VC++ when I need to specify an array bound for a class member variable I do it this way:

 class Class {

 private:
     static const int numberOfColors = 16;
     COLORREF colors[numberOfColors];
 };

(please don't tell me about using std::vector here)

This way I have a constant that can be used as an array bound and later in the class code to specify loop-statement constraints and at the same time it is not visible anywhere else.

The question is whether this usage of static const int member variables only allowed by VC++ or is it typically allowed by other widespread compilers?

like image 414
sharptooth Avatar asked Aug 25 '09 11:08

sharptooth


2 Answers

This is valid C++ and most (all?) reasonably modern compilers support it. If you are using boost, you can get portable support for this feature in the form of BOOST_STATIC_CONSTANT macro:

class Class {
 private:
     BOOST_STATIC_CONSTANT(int, numberOfColors = 16);
     COLORREF colors[numberOfColors];
 };

The macro is expanded to static const int numberOfColors = 16 if the compiler supports this, otherwise it resorts to enum { numberOfColors=16 };.

like image 94
Bojan Resnik Avatar answered Nov 09 '22 10:11

Bojan Resnik


That behavior is valid according to the C++ Standard. Any recent compiler should support it.

like image 37
A. L. Flanagan Avatar answered Nov 09 '22 08:11

A. L. Flanagan