schtandard
schtandard

Reputation: 510

Using `constexpr` with array initialization

I know that in C++11, I can write

class foo {
    static constexpr const char *one = "one";
}

However, when I try to do the same for an array

class bar {
    static constexpr const float prim[4] = {2, 3, 5, 7};
}

(and reference it later on) I get an undefined reference linker error.

Is this just not possible for arrays or am I missing something in the syntax?

Upvotes: 3

Views: 5813

Answers (1)

skypjack
skypjack

Reputation: 50540

Static constexpr data member declarations aren't definitions in C++11/14, therefore you cannot odr-use prim.
To work around it, put the following statement somewhere in your cpp file as you would do with any other non-constexpr static data member:

constexpr const float bar::prim[4];

In other terms, this returns an undefined reference:

struct bar {
    static constexpr const float prim[4] = {2, 3, 5, 7};
};

int main() {
    auto *foo = bar::prim;
}

This doesn't:

struct bar {
    static constexpr const float prim[4] = {2, 3, 5, 7};
};

constexpr const float bar::prim[4];

int main() {
    auto *foo = bar::prim;
}

Because in the second case you are actually defining prim other than declaring it and thus you can get its address, use it by means of a reference, and so on...

Upvotes: 3

Related Questions