Hernan Villanueva
Hernan Villanueva

Reputation: 531

Access static constexpr std::array without out-of-class definition

I have a class that defines some arrays.

Points.hpp

class Points {

public:

    static constexpr std::array< double, 1 > a1 = { {
            +0.0 } };

    static constexpr std::array< double, 2 > a2 = { {
            -1.0 / std::sqrt( 3.0 ),
            +1.0 / std::sqrt( 3.0 ) } };

};

My main file then uses these arrays.

main.cpp

#include "Points.hpp"

int main()
{
    // Example on how to access a point.
    auto point = Points::a2[0];

    // Do something with point.
}

When I compile my code, using C++11 and g++ 4.8.2, I get the following linker error:

undefined reference to `Points::a2'

I attempted to create a Points.cpp file so that the compiler can create an object file from it.

Points.cpp

#include "Points.hpp"

But that did not fix the linker error.

I was under the impression that it was possible to initialize variables as static constexpr in C++11 in the class declaration, and then access them the way I'm doing it, as shown in this question: https://stackoverflow.com/a/24527701/1991500

Do I need to make a constructor for Points and then instantiate the class? What am I doing wrong?

Any feedback is appreciated! Thanks!

Upvotes: 3

Views: 3704

Answers (1)

Hernan Villanueva
Hernan Villanueva

Reputation: 531

As per @dyp suggestion, I looked into the definition of static data members.

My problem requires me to define the static member variables of my Points class.

Following the examples in these questions:

Is a constexpr array necessarily odr-used when subscripted?

and

Defining static members in C++

I need to add:

// in some .cpp
constexpr std::array< double, 1 > Points::a1;

Upvotes: 2

Related Questions