c++ - 类模板中的静态成员变量

标签 c++

当您有一个包含静态成员的(非模板化)类时,例如:

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;

所以,如果类模板Foofoo.hpp 中定义, 和 translation_unit1.cpptranslation_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/

相关文章:

c++ - 在 C++ 中,什么是虚拟基类?

c++ - 一些面试真题C++

c++ - 我应该使用 GTK+ 还是 QT

c++ - 正确重载 new/delete new[]/delete[]

C++ 系统时间返回相同的错误值

c++ - SQLite3_exec 回调未在 C++ 中使用 INSERT 语句调用

c++ - AscW 等效于 C++ 中的 VB

c++ - 从 std::thread 在主线程上执行回调函数

c++ - QML 引擎无法正确导入 C++ 模型

c++ - 无法从文件中正确读取整数 C++