Search code examples
c++stdarray

Initialize stdarray with size depending on const class member


Can somebody explain to me why the following results in the error "non-type template argument is not a constant expression" and how to deal with it?

#include <array>

class Test
{
    public:
    Test(int n) : num_requests(n/2){};
    const int num_requests;
    
    void func()
    {
        std::array <int,num_requests> test_array;
    };
};

Solution

  • Use a template "argument" like this:

    #include <array>
    
    template <int n>
    struct Test
    {
        void func()
        {
            std::array <int,n/2> test_array;
        };
    };
    
    int main() {
        auto t = Test<10>{};
        t.func();
    }