类类型的静态constexpr字段在g++中给出链接时间错误
Class-typed static constexpr field giving link-time errors in g++
我今天测试了以下代码片段:
#include <iostream>
struct Literal {
constexpr operator int() const { return 0; }
};
struct Class {
constexpr static const Literal field0 = Literal();
};
int main(void) {
std::cout << "Class::field0: " << Class::field0 << std::endl;
return 0;
}
它编译时没有错误(G++6.2.1),但不幸的是,我在生成可执行文件时遇到了一个链接错误:
/tmp/ccao6eTy.o: In function `main':
test-constexpr-static-field.cpp:(.text+0xa): undefined reference to `Class::field0'
collect2: error: ld returned 1 exit status
[Finished in 0.3s with exit code 1]
阅读本页,我看到了这样的解释:
如果LiteralType的静态数据成员被声明为constexpr,它必须使用初始化器进行初始化,其中每个表达式是一个常量表达式,就在类定义内(…)。
然后我找到了什么是LiteralType的定义,我看到了:
文字类型是以下任意一种:
- 可能是具有以下所有属性的cv限定类类型:
- 有一个平凡的析构函数
- 是
- 聚合类型
- 具有至少一个constexpr(可能是模板)构造函数的类型,该构造函数不是复制或移动构造函数
- 一个闭包类型(从C++17开始)
- 所有非静态数据成员和基类都是非易失性文本类型
是否存在Literal
不符合LiteralType
的情况?在我看来,它有一个琐碎的构造函数,甚至没有内部状态来避免聚合类型或文本类型上的非静态字段的任何麻烦问题。
但考虑到它确实符合(主要是因为程序编译没有错误),为什么会出现链接时间错误?这可能是一个G++错误吗?
显然,我需要在类外添加一个定义。
工作示例:
#include <iostream>
struct Literal {
constexpr Literal() = default;
constexpr operator int() const { return 0; }
};
struct Class {
constexpr static const Literal field0 = Literal();
};
// This is needed to avoid undefined reference errors
// This is a definition. Very strange.
constexpr const Literal Class::field0;
int main(void) {
std::cout << "Class::field0: " << Class::field0 << std::endl;
return 0;
}
来源:https://stackoverflow.com/a/8016853/3962396
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- Visual Studio mkl_link_tool.exe链接错误
- C++ 实现模板单例类时出现链接错误
- 使用类模板的方法链接错误
- MySQL C++连接器链接错误
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 运行 C++ 单元测试时LNK2005链接错误
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 链接错误,包括我创建的相同头文件 - C++
- 在Embarcadero C++ Builder中生成的DLL未解决的外部链接错误
- 使用标头保护的多个定义链接错误
- 链接错误:未定义对 stdscr 和 wgetch 的引用
- 使用 Vivek 的 Vcam / 捕获源过滤器构建/链接错误
- 升压program_options中的链接错误
- 使用 g++ 预处理器进行替换会导致链接错误
- 在调试配置中编译工作正常,但发布会给出链接错误
- 相邻矩阵设置链接错误
- 包含常量变量并包含在多个文件中的标头的链接错误
- C++链接错误,我理解但无法解决
- 是什么导致macOS Mojave上的GoogleTest链接错误