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?
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With