首页 > 解决方案 > 还使用“外部模板类”语法时模板类静态成员变量的特化

问题描述

我有一个模板类,我只打算与我提前知道的 3 种不同类型一起使用。为了减少代码膨胀,我想尽可能多地保留在标题之外。模板类还具有静态变量,这些变量必须根据专业化而有所不同。

我尝试在使用 Visual C++ 19.15.26729 的 Windows 和使用 XCode 和 clang-900.0.39.2 的 Mac 上实现这一点。我需要不同的代码来满足每个编译器,更糟糕的是编译器抱怨彼此的“好”版本的程序。

这是一个最小的例子:

// A.h
template<typename T>
class A
{
public:
    static T x;
};

// template<> int A<int>::x; // PROBLEMATIC PART

extern template class A<int>;
// A.cpp
#include "A.h"

template<> int A<int>::x = 42;

template class A<int>;
// main.cpp
#include "A.h"

int main()
{
    return A<int>::x;
}

上面的代码(带有注释的行)在 VC++ 上编译得很好,但是 clang 抱怨: Explicit specialization of 'x' after instantiation

这个问题的答案有帮助:使用“外部模板”时,专门化模板的正确方法是什么?

未注释它在template<> int A<int>::x;Xcode 上编译得很好,但是 Visual C++ 抱怨:

1>A.cpp(3): error C2086: 'T A<int>::x': redefinition
1>        with
1>        [
1>            T=int
1>        ]
1>A.h(9): note: see declaration of 'x'
1>A.cpp(3): error C2086: 'T A<T>::x': redefinition
1>        with
1>        [
1>            T=int
1>        ]
1>A.h(6): note: see declaration of 'A<int>::x'

我的方法从根本上是错误的吗?它是编译器错误吗?也许它是只有一个编译器支持的功能,如果是这样 - 根据标准哪个版本是正确的?

标签: c++templatesvisual-c++clangtemplate-specialization

解决方案


这确实是微软编译器中的一个错误,已经记录在他们的积压工作中。关注此问题以获取更新:https ://developercommunity.visualstudio.com/content/problem/319447/explicit-specialization-of-static-data-member-inco.html


推荐阅读