I have the following files:
test.hpp
class Test {
static constexpr const char* array[] {
"hello",
"world",
"!"
};
public:
void do_stuff();
};
test.cpp
void Test::do_stuff() {
for(int i = 0; i < 3; ++i) {
std::cout << array[i];
}
}
int main() {
Test object;
object.do_stuff();
}
This fails with the following linking error:
undefined reference to `Test::array'
So how can I define a constexpr array and then iterate over it?
static members need an offline declaration or explicit inline:
From C++17:
inline static constexpr const char* array[] {
Other solution:
#include <iostream>
class Test {
static constexpr const char* array[] {
"hello",
"world",
"!"
};
public:
void do_stuff();
};
constexpr char* Test::array[];
void Test::do_stuff() {
for(int i = 0; i < 3; ++i) {
std::cout << array[i];
}
}
int main() {
Test object;
object.do_stuff();
}
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