C++ 语言标准规定了标准库中有关模板组件的以下内容:
The effects are undefined...if an incomplete type is used as a template argument when instantiating a template component, unless specifically allowed for that component (C++11 §17.6.4.8/2).
以下是否会导致 std::vector
的实例化?类模板?
class X;
std::vector<X> f(); // Declaration only; we will define it when X is complete
换个说法,在函数声明中 std::vector<X> f();
, 是 std::vector
用参数 X
实例化?或者,是 std::vector<X>
直到 f()
才被实例化是否使用或定义了 odr?
同样,以下是否会导致 std::vector
的实例化?类模板?
class X;
typedef std::vector<X> XVector; // We will complete X before we use XVector
当我使用 std::vector
时在这些示例中,问题同样适用于所有模板。
最佳答案
§ 14.7.1\1 隐式实例化 [temp.inst]
Unless a class template specialization has been explicitly instantiated (14.7.2) or explicitly specialized (14.7.3), the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program. The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, static data members and member templates; and it causes the implicit instantiation of the definitions of member anonymous unions. Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.
§ 8.3.5\9 函数 [dcl.fct]
Types shall not be defined in return or parameter types. The type of a parameter or the return type for a function definition shall not be an incomplete class type (possibly cv-qualified) unless the function definition is nested within the member-specification for that class (including definitions in nested classes defined within the class).
§ 3.1\2 声明和定义 [basic.def]
A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function-body, it declares a static data member in a class definition (9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), or it is a typedef declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute-declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).
只有在必需时才会被实例化。我在任何地方都找不到明确的定义,但第二句话说那些声明不是定义,这对我来说似乎是一样的。
关于c++ - 在声明 "std::vector<X> f();"中, "std::vector<X>"是实例化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7730874/