Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

const int, member array size

My code basically:

class myclass : public singleton<myclass> {
    public:
        myclass();
    private:
        const float myfloat = 6000.0f;
        const int sz_arr = (int)myfloat;

        int arr[sz_arr];  // compiler complains about this line
};

Need to create arr at compile-time. Size of arr is known at compile-time! Ought to be computed based on myfloat value. How to achieve it? Also, myclass is singleton, only one instance of it is ever going to be created.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Firstly, sz_arr can’t be used to specify the size of the array, you need to make it static. And mark myfloat as constexpr to make it known at compile-time (and better for sz_arr too).

class myclass : public singleton<myclass> {
    public:
        myclass();
    private:
        constexpr static float myfloat = 6000.0f;
        constexpr static int sz_arr = myfloat; // implicit conversion is enough

        int arr[sz_arr]; 
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading