Peter234
Peter234

Reputation: 1052

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?

Upvotes: 4

Views: 2593

Answers (2)

Adrian Maire
Adrian Maire

Reputation: 14815

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

}

Upvotes: 3

dfrib
dfrib

Reputation: 73176

Consider using std::array instead of a raw array:

#include <array>
#include <iostream>

struct Test {
    static constexpr std::array<const char*, 2> arr{"hello", "world"};
};

// Out-of class definition.
const std::array<const char*, 2> Test::arr;

int main() {
    for (const auto c : Test::arr) { std::cout << c << " "; }
    // hello world
}

note the out-of-class definition needed if the arr static data member is ODR-used.

Upvotes: 0

Related Questions