user3437441 user3437441 - 2 months ago 11
C++ Question

Strange error C2131: expression did not evaluate to a constant in VC 2015

// foo.hpp file
class foo
{
public:
static const int nmConst;
int arr[nmConst]; // line 7
};
// foo.cpp file
const int foo::nmConst= 5;


Compiler VC 2015 return error:


1>foo.h(7): error C2131: expression did not evaluate to a constant

1> 1>foo.h(7): failure was caused by non-constant arguments or

reference to a non-constant symbol 1> 1>foo.h(7): note: see usage of
'nmConst'


Why? nmConst is static constant with value defined in *.cpp file.

Answer

It's possible to use static const int member as an array size, but you'll have to define this member within class in your .hpp file like so:

class foo
{
public:

    static const int nmConst = 10;
    int arr[nmConst];

};

This will work.

P.S. About the logic behind it, I believe compiler wants to know size of the array member as soon as it encounters class declaration. If you leave static const int member undefined within the class, compiler will understand that you're trying to define variable-length array and report an error (it won't wait to see if you actually defined nmconst someplace).