Initialize a multidimensional static const array with the alleged dimensions inside the class definition

With C ++ 11, you can initialize the built-in static const types inside the class definition, for example:

class A {
public:
    static const unsigned int val = 0; //allowed
};

However, by doing this in Visual C ++ 2013 with an array, I can report 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 initializer in the class." Instead, I am forced to do the following:

class C {
public:
    static const unsigned int val[][2];
};

const unsigned int C::val[][2] = { { 0, 1 } };

This is unsuccessful because I have code that depends on the size of val, and I want to be able to change the contents of val without thinking of returning and changing the constant somewhere. Is there any other way to do this that allows me to use sizeofon valfrom anywhere in the file below the declaration?

+4
1

constexpr (clang gcc ):

class B { 
public:
    static constexpr const unsigned int val[][2] = { { 0, 1 } };
    //     ^^^^^^^^
};

, .

Visual Studio CTP 2013 ( "" , ) constepxr, .

EDIT:

constexpr (, , ), :

class C {
public:
    static const unsigned int val[][2];
};

const unsigned int C::val[][2] = { { 0, 1 } };

( ), sizeof ( , ): ;

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;
}
+6

Source: https://habr.com/ru/post/1547845/


All Articles