2

How to initialize static std:array that uses static const variable as size? I tried searching for similar questions but std::array is relatively new so theres not much to be found.

// ExampleClass.h
class ExampleClass {
    public:
        static const size_t NUMBER_OF_INDEXES = 5;
    private:
        static std::array<int, NUMBER_OF_INDEXES> myArray;
};

2 Answers 2

4

Like any other static data member, ExampleClass::myArray should have an out-of-line definition in exactly one translation unit, where you write down its type and its qualified name as usual:

std::array<int, ExampleClass::NUMBER_OF_INDEXES> ExampleClass::myArray = {1, 2, 3, 4, 5};
Sign up to request clarification or add additional context in comments.

Comments

0

Works fine with newer standards/compilers. I tried your code and it runs fine when using C++20 or C++23:

#include <array>
#include <stdint.h>
#include <iostream>

class ExampleClass {
    public:
        static const std::size_t NUMBER_OF_INDEXES = 5;
    private:
        static std::array<int, NUMBER_OF_INDEXES> myArray;
    public:
        void printSize(){
            std::cout << myArray.size() << std::endl;
        }
    
};

int main()
{
    ExampleClass obj;
    obj.printSize();
    return 0;
}

https://onlinegdb.com/lVycEuQmE

P.S. For those who opened the question wondering if they can convert C-style array to std::array - yes, you can using C++20 std::to_array()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.