遍历 constexpr 数组

Loop over constexpr array

我有以下文件:

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

}

失败并出现以下链接错误:

undefined reference to `Test::array'

那么如何定义一个 constexpr 数组然后对其进行迭代?

static 成员需要离线声明或显式 inline:

来自 C++17:

inline static constexpr const char* array[] {

其他解决方案:

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

}

考虑使用 std::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
}

注意如果 arr 静态数据成员是 ODR-used,则需要 out-of-class 定义。