Search code examples
c++arraysc++11staticcompile-time-constant

How to define the size of an array that is a static member of a non instanciable class?


I'm writing a class I don't want to instantiate. All its members are static. This class represents a peripheral of a microcontroller. Since there is only one instance of that peripheral in the microcontroller doesn't make sense to me create instances of that class. The class only groups the data and functions of that peripheral.

One of the data members of the class is an array whose size the user of the class should define at compile time. If I could create objects of this class I know I could initialize consts in the initializer list of a constructor, but I really don't want to create instances of this class. Maybe I could use templates and set the array size as the template parameter, but I would need to use something like my_class<5>::do_something() for every member call. Is there a simpler way to solve this problem? I'd like to make my class something like this:

class my_class
{
private:
    static const int _size;
    static int _array[_size];
public:
    static void array_size(int size) { _size = size; }
    static void do_something() { /* .... */ } 
};

Solution

  • Consider using class template parametrized with constexpr array size and then create an alias:

    #include <array>
    
    template <std::size_t Size>
    class my_class_impl {
    private:
        static constexpr std::size_t size = Size;
        static std::array<int, Size> arr;
    public:
        static void do_something() { /* .... */ }
    };
    
    template <std::size_t Size>
    std::array<int, Size> my_class_impl<Size>::arr;
    
    using my_class = my_class_impl<10>;
    
    int main() {
        my_class::do_something();
    }