dimanche 28 février 2021

C++ static constant array initialization inside class

I want to create a constant and static integer array as a public class variable. It is neat to define it and initialize it right away. See code below for complete example.

#include <iostream>

class Foo {
public:
    constexpr static int arr[3][2] = {
            {1, 2},
            {3, 4},
            {5, 6}
    };
};

int main() {
    for (int i = 0; i < 3; i++) {
        std::cout << "Pair " << Foo::arr[i][0] << ", " << Foo::arr[i][1] << std::endl;
    }
    return 0;
}

However, compiling code above using g++ --std=c++11 test.cpp produces

/usr/bin/ld: /tmp/ccc7DFI5.o: in function `main':
test.cpp:(.text+0x2f): undefined reference to `Foo::arr'
/usr/bin/ld: test.cpp:(.text+0x55): undefined reference to `Foo::arr'
collect2: error: ld returned 1 exit status

Is this not possible in C++ ? More likely I am missing some part about C++ and its static variable initialization policy.

Aucun commentaire:

Enregistrer un commentaire