Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over constexpr array

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?

like image 339
Peter234 Avatar asked Oct 28 '25 14:10

Peter234


1 Answers

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();

}
like image 100
Adrian Maire Avatar answered Oct 30 '25 05:10

Adrian Maire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!