c++ - 模板中的静态变量未定义

标签 c++

为什么这段代码不工作并给出“未定义的最大值”?

#include <iostream>
using namespace std;

template<typename T>
struct Foo {
  static T const max;
};

template<> struct Foo<int> { // Specialization
    static int max; 
};

template<typename T> T const Foo<T>::max = 22;

template struct Foo<int>;

int main() {

    struct Foo<int> ma;
    cout << ma.max;

    return 0;
}

我定义了静态变量并实例化了模板(我相信显式实例化在这里没有用)。

怎么了?

最佳答案

template<typename T> T const Foo<T>::max = 22;是一般情况下的定义,不针对特殊情况。

您还必须定义 int Foo<int>::max = 22;对于 int 特化。

关于c++ - 模板中的静态变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24323390/

相关文章:

c++ - 错误 :no appropriate constructor found, 即使我做了一个,c++

c++ - 我是否应该始终检查 nullptr 的成员指针?

python - 找不到 GLIBCXX_3.4.29

c++ - 使用预编译 header 减少 clang 编译时间

c++ - 简单的 getter/accessor 防止矢量化 - gcc 错误?

c++ - 这个简单的哈希函数背后的逻辑是什么?

c++ - 具有多维数组错误的简单 C++ 程序?

c++ - OpenGL 退化 GL_TRIANGLES 共享相同的顶点

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

c++ - 如何检查对象是否在数组中?