1

The following code works on gcc but fails on VS2012

class test_base{};

template<class DERIVED >
        class test_CRTP : public test_base
        {
                public:
                        const static int n_size;
        };

        //DEFAULT INITIALIZATION
template< class DERIVED >
        const int test_CRTP<DERIVED>::n_size = 3;

        //TEMPLATE SPECIALIZATION
        class test_spec : public test_CRTP<test_spec>{};


template<class test_T>
class MyClass{
public:
        void my_method(){
                int my_array[test_T::n_size];   //<-VS doesn't like this
        }
};

int main()
{
        MyClass<test_spec> oClass;
        oClass.my_method();
        return 0;
}

Error is:

error C2057: expected constant expression

Is my code non standard compliant or is VS wrong?

Is this fixed on newer versions?


EDIT: Based on http://webcompiler.cloudapp.net/, error persists on version 19.00.23720.0

Compiled with  /EHsc /nologo /W4 /c
main.cpp
main.cpp(26): error C2131: expression did not evaluate to a constant
main.cpp(26): note: failure was caused by non-constant arguments or reference to a non-constant symbol
main.cpp(26): note: see usage of 'n_size'
main.cpp(25): note: while compiling class template member function 'void MyClass<test_spec>::my_method(void)'
main.cpp(33): note: see reference to function template instantiation 'void MyClass<test_spec>::my_method(void)' being compiled
main.cpp(32): note: see reference to class template instantiation 'MyClass<test_spec>' being compiled
2
  • You can try at webcompiler.cloudapp.net Commented Mar 21, 2016 at 19:16
  • @Niall Thanks for the link, seems I had no luck. Commented Mar 21, 2016 at 19:25

1 Answer 1

1

Clang and gcc accept the code as posted.

MSVC is unhappy with the out of class initialisation of the const static, moving it to in the class allows MSVC to compile it. This issue is present in v19.00.23720.0 of the compiler (as of this posting, online here).

template <class DERIVED>
class test_CRTP : public test_base {
 public:
  const static int n_size = 3;
  //                     ^^^^^ moved it into the class.
};
Sign up to request clarification or add additional context in comments.

1 Comment

So no way to override a static const member variable :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.