Why I Am Getting This Error: Constexpr' Is Not Valid Here

Why I Am Getting This Error: Constexpr' Is Not Valid Here

I have this code:

class myClass
{
        constexpr int x = 4;
};

and on visual studio 2015, I am getting this error:

'constexpr' is not valid here

Why I am getting this error? I want a const static variable that I can initlaize it on header file.

In the next step I want to change my class to a template, but this constant is not related to the type of clas.

5

2 Answers

Non-static data members cannot be declared as constexpr. Use

class myClass
{
    static constexpr int x = 4;
};

instead.

I want a const static variable that I can initlaize it on header file

if your main concern is constant value which is shareable to all template type instances, then you can just change to the below:

class myClass
{
    static const int x = 4;
};

If your concern is the memory space (although it is shared between all instances), you can just use compilation pre-processing solution (i.e. #Define X 4)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.