首页 > 解决方案 > 为什么这个 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++templates

解决方案


简短回答:您需要激活 C++17 或升级您的编译器

长答案:即使是 constexpr 变量也需要定义。当您 ODR 使用 constexpr 变量时,您需要为其添加定义。

在 C++17 中,类类型定义的 constexpr 变量部分默认是内联的。内联变量像内联函数一样生成它们的定义。

如果您不能拥有 C++14,则需要一个不符合要求的定义。


推荐阅读