Search code examples
c++arraystemplatesmemory-managementstdarray

C++ zero-size array that requires no memory space?


When declaring a member variable of a templated class, is there a way to make it require zero memory depending on the value of some template parameter?

An example is to define something like std::array<T,n> that would require zero space when n==0.

For example:

template<int num_optional_args> class C {
    int some_variable;
    std::array<int,num_optional_args> optional_args;
};

Is there a way to eliminate the overhead of the optional_args when num_optional_args==0?

Most implementations of std::array<T,n> reserve space for one T element even when n==0.

Is there another means that would reserve zero space? Why is this not part of the C++ standard?


Solution

  • You could specialize your type so that optional_args doesn't exist when the number is zero. If you need the object to exist then the only way in which an object can exist and can be referred to while in fact taking up no space is through the empty base class optimization.

    You might use that in the following way:

    template<int num_optional_args>
    class optional_args {
        std::array<int,num_optional_args> args
    public:
        // whatever interface you want for the optional args.
        void foo(int n) {
            if (n < num_optional_args)
                args[n];
            throw std::runtime_error("out of range");
        }
    };
    
    template<>
    class optional_args<0> {
    public:
        // whatever interface you want for the optional args, specialized for 0 args.
        void foo(int n) {
            throw std::runtime_error("out of range");
        }
    };
    
    template<int num_optional_args>
    class C : optional_args<num_optional_args> {
        int some_variable;
        void bar() {
            for (int i=0; i<num_optional_args; ++i) {
                optional_args::foo(i);
            }
        }
    };