当您有一个包含静态成员的(非模板化)类时,例如:
class Foo
{
public:
static int x;
};
然后 Foo::x
必须在一个且只有一个翻译单元中定义,否则编译器会提示多个定义。所以在 somefile.cpp
你必须定义它:
int Foo::x = 10;
这样,任何访问 Foo::x
的翻译单元正在访问相同的内存地址。
但是如果 Foo
怎么办?是类模板吗?
template <class T>
class Foo
{
public:
static int x;
};
现在,Foo<T>::x
可以在头文件中定义:
template <class T>
int Foo<T>::x = 10;
所以,如果类模板Foo
在 foo.hpp
中定义, 和 translation_unit1.cpp
和 translation_unit2.cpp
两者都包括 foo.hpp
, 将 Foo<T>::x
的内存地址对于模板类 Foo 的某些实例,(例如 Foo<int>::x
)每个翻译单元都不同吗?
最佳答案
这很好,在这种情况下,如果我们看到 C++ 标准部分 3.2
一个定义规则<,编译器将确保只有一个实例,在 header 中定义它/em> 段 6 说(强调我的):
There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function
然后我们可以转到 14.5.1.3
部分 类模板的静态数据成员 1 段说:
A definition for a static data member may be provided in a namespace scope enclosing the definition of the static member’s class template.
并提供了以下示例:
template<class T> class X {
static T s;
};
template<class T> T X<T>::s = 0;
关于c++ - 类模板中的静态成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19366615/