katherinejohnson
katherinejohnson

Reputation: 149

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;
    };
};

Upvotes: 0

Views: 55

Answers (1)

Lasersk&#246;ld
Lasersk&#246;ld

Reputation: 2235

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();
}

Upvotes: 3

Related Questions