c++ - 实例化模板是否实例化其静态数据成员?

标签 c++ templates

关于显式实例化(当模板在 header 中声明并在 cpp 文件中定义时使用 IIRC,否则链接器在其他地方使用时将无法找到它),如果模板具有静态成员变量,显式实例化是否也会实例化并创建静态成员变量?

最佳答案

如果显式实例化类模板,所有非模板成员都将被实例化,包括 static 数据成员,只要它们也有定义。例如:

template <typename T>
struct foo {
    static int static_data;
    void non_template_member() {}
    template <typename S>
    void template_member(S) {}
};

template <typename T>
int foo<T>::static_data = 0;

template struct foo<int>;
template struct foo<double>;

底部的显式实例化为类型 intdouble 创建了 static_datanon_template_member() 的定义>。 template_member(S) 不会有定义,因为它仍然是一个开放集。

如果您没有为 static_data 提供 [templated] 定义,它不会实例化相应的定义。

标准的相关部分是 14.7.2 [temp.explicit] 第 8 段:

An explicit instantiation that names a class template specialization is also an explicit instantiation of the same kind (declaration or definition) of each of its members (not including members inherited from base classes and members that are templates) that has not been previously explicitly specialized in the translation unit containing the explicit instantiation, except as described below.

如果没有成员定义,static 成员只会被声明,显式实例化只会看到被实例化的声明。通过定义,显式实例化成为定义。

关于c++ - 实例化模板是否实例化其静态数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24326311/

相关文章:

C++ 模板和外部函数声明

c++ - 将异步操作的处理程序绑定(bind)到另一个类的非静态成员

C++ const 基于输入的静态启动

c++ - 使用虚函数转发声明模板类的实例

c++ - 如果不是抽象则调用基类方法

C++ 模板字符串连接

C++ 多态性和可变参数模板

c++ - 如何在 C++ 中表达一系列数组位置?

c++ - C/C++ : Write and Read Sockets

c++ - 在 C++ 中读取和写入西里尔文文件