Home > Back-end >  const int, member array size
const int, member array size

Time:11-10

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.

CodePudding user response:

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]; 
};
  • Related