Initialize static const multidimensional array with inferred dimensions inside class definition
c++, c++11, visual-c++, visual-studio-2013
Solution
Your array must be a constexpr (clang and gcc specify it in their error messages) :
class B {
public:
static constexpr const unsigned int val[][2] = { { 0, 1 } };
// ^^^^^^^^
};
See it working here.
Visual Studio CTP 2013 (a "beta" version, that should be avoided for production) provides support for `constepxr`, which should be available in future releases, too.
EDIT :
If your compiler does not support `constexpr` (hopefully for you, not for too long), then you cant do in-class initialization of your static array, and must do the old way :
class C {
public:
static const unsigned int val[][2];
};
const unsigned int C::val[][2] = { { 0, 1 } };
If your array type is complete (if you declare all the array dimensions), then `sizeof` can be applied (the compiler knows how many elements to expect) : ;
class C {
public:
static const unsigned int val[2][2]; // Specify all dimensions.
void foo() { cout << sizeof(C::val); } // OK
};
const unsigned int C::val[][2] = { { 0, 1 } , { 2, 3 } };
int main() {
C c;
c.foo();
return 0;
}
Problem
Since C++11, one can initialize static const built-in types inside a class definition, like so: ``` class A { public: static const unsigned int val = 0; //allowed }; ``` However, doing this in Visual C++ 2013 with an array gives me an error telling me that this is not allowed: ``` class B { public: static const unsigned int val[][2] = { { 0, 1 } }; //not allowed }; ``` The error message simply reads "a member of type const unsigned int [][2] cannot have an in-class initializer." Instead, I'm forced to do the following: ``` class C { public: static const unsigned int val[][2]; }; const unsigned int C::val[][2] = { { 0, 1 } }; ``` This is unfortunate because I have code which relies on the size of val, and I want to be able to change the contents of val without having to remember to go back and change a constant somewhere. Is there a different way of doing this that allows me to use `sizeof` on `val` from any point in the file below the declaration?