c++ - 为什么这个 c++ 模板需要参考?
问题描述
我尝试使用规范打印类型,但这不起作用。
template<typename T>
struct print_type {
static constexpr char const value[] = "unknown";
};
template<>
struct print_type<void> {
static constexpr char const value[] = "void";
};
template<>
struct print_type<int> {
static constexpr char const value[] = "int";
};
int main() {
cout << print_type<void>::value << endl;
}
编译器显示:
Undefined symbols for architecture x86_64:
"print_type<void>::value", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
解决方案
简短回答:您需要激活 C++17 或升级您的编译器
长答案:即使是 constexpr 变量也需要定义。当您 ODR 使用 constexpr 变量时,您需要为其添加定义。
在 C++17 中,类类型定义的 constexpr 变量部分默认是内联的。内联变量像内联函数一样生成它们的定义。
如果您不能拥有 C++14,则需要一个不符合要求的定义。
推荐阅读
- javascript - chart.js 雷达在值为 12 时显示 0
- javascript-objects - 如何防止 Object.keys() 排序?
- javascript - 无法对使用 HOOK 实现的未安装组件执行 React 状态更新
- angular - 是否可以使用 ng-content 将 mat-options 传递给我的自定义 mat-select 组件?
- docker - 我无法在 ubuntu 17.10 上安装 docker
- python - 检查文本文件更新结果打印输出两次
- macos - 在 Mac 中构建移动应用程序时,Jenkins 构建命令失败
- ios - 适用于所有 Xcode 版本的 Swift 框架
- javascript - 为什么数组在响应中总是空的?
- css - css - 将全宽块定位在居中页面后面