如何访问结构中定义的 constexpr 字符串?

How to access a constexpr string that is defined in a struct?

如何从结构中正确访问字符串 "bye"?

#include <iostream>
static constexpr char hi[] = "hi";
struct S{ static constexpr char bye[] = "bye"; };

int main(int argc, char *argv[]) {
  typedef struct S ST;

  std::cout << hi << std::endl;              // this prints "hi" 
  std::cout << sizeof(ST::bye) << std::endl; // this correctly prints 4
  std::cout << ST::bye << std::endl;         // this does not compile with "undefined reference"
}

我正在使用一个 c++ 框架,该框架具有这种格式的一些配置(甚至在多重嵌套结构中),以使其值在编译时可用。我对 C++ 的了解还不够深入,无法掌握这里的根本问题。我也不能争论为什么选择这种实现配置的方法并且不能改变它。

这可以通过在结构外重新定义静态 constexpr 来实现:

#include <iostream>
static constexpr char hi[] = "hi";
struct S{ static constexpr char bye[] = "bye"; };

constexpr char S::bye[]; // <<< this line was missing

int main(int argc, char *argv[]) {
  typedef struct S ST;

  std::cout << hi << std::endl;              // this prints "hi" 
  std::cout << sizeof(ST::bye) << std::endl; // this correctly prints 4
  std::cout << ST::bye << std::endl;         // Now this prints "bye"
}

或者通过使用 c++17 进行编译,这使得它已过时。

相关链接:

  • What does it mean to "ODR-use" something?