Roger_88
Roger_88

Reputation: 477

How do I declare a const size_t inside a class?

I'm trying to use C++ arrays in my class:

#include <array>
#include <iostream>

using namespace std;

class Test {
    private:
        const size_t NCOL = 4;
        array<int, NCOL> row;

    public:
        Test(){}
        ~Test(){}
};  

int main() {
    Test t;
    return 0;
}

But I'm getting the following error messages and I don't know why:

test.cpp:9:14: error: invalid use of non-static data member ‘Test::NCOL’
   array<int, NCOL> row;
              ^~~~

test.cpp:8:23: note: declared here
   const size_t NCOL = 4;
                       ^

test.cpp:9:14: error: invalid use of non-static data member ‘Test::NCOL’
   array<int, NCOL> row;
              ^~~~

test.cpp:8:23: note: declared here
   const size_t NCOL = 4;
                       ^

test.cpp:9:14: error: invalid use of non-static data member ‘Test::NCOL’
   array<int, NCOL> row;
              ^~~~

test.cpp:8:23: note: declared here
   const size_t NCOL = 4;
                       ^

test.cpp:9:18: error: template argument 2 is invalid
   array<int, NCOL> row;

How can I fix this?

Upvotes: 0

Views: 522

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597650

The answer is right there in the error messages:

invalid use of non-static data member ‘Test::NCOL’

NCOL is not static, so it is a data member of every instance of Test, and gets its value at runtime when Test is constructed. You can't use runtime data values in template parameters.

Make NCOL be static instead, then the compiler can use it as a compile-time constant like you are intending it to be:

static const size_t NCOL = 4;

Upvotes: 1

Related Questions