如何从结构中正确访问字符串“ 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进行编译,这使得它已过时。
相关链接:-constexpr static member before/after C++17-What does it mean to "ODR-use" something?