我正在使用包含静态变量的模板类。代码结构如下。
Header.h
template<class T> class Foo
{
public:
static int count;
Foo() {
count++;
}
void printCount() {
cout << count << endl;
}
};
template<class T> int Foo<T>::count;
源码.cpp
#include "Header.h"
template<> int Foo<int>::count = 5;
main.cpp
#include <iostream>
using namespace std;
#include "Header.h"
int main()
{
Foo<int> obj1;
Foo<int> obj2;
obj1.printCount();
obj2.printCount();
return 0;
}
xcode8.3.3 上的输出是:
7
7
而 Visual Studio 2015 上的输出是:
2
2
即特定实例化会覆盖 xcode8.3.3 中的通用实例化,但不会覆盖 Visual Studio 2015 中的通用实例化。
有人可以解释这种行为差异吗?
提前致谢。
虽然您的代码包含约束违规,但实际上使其格式良好并维护静态初始化的一个位置并不太困难。对于 C++ 标准来说,位于[温度解释规范]/13 https://timsong-cpp.github.io/cppwp/n4659/temp.spec#temp.expl.spec-13:
模板或模板的静态数据成员的显式特化
静态数据成员模板的显式专业化是
定义(如果声明包含初始值设定项);否则,它
是一个声明。 [ 注意:a的静态数据成员的定义
需要默认初始化的模板必须使用
大括号初始化列表:
template<> X Q<int>::x; // declaration
template<> X Q<int>::x (); // error: declares a function
template<> X Q<int>::x { }; // definition
——《尾注》]
上面的内容意味着只需添加这一行
template<> int Foo<int>::count; // declaration
在底部Header.h足以让所有翻译单位知道Foo<int>::count
存在于“某处”。唯一真正的定义可能仍然存在源码.cpp.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)