成员函数实例化

Member function instantiation

本文关键字:实例化 函数 成员      更新时间:2023-10-16

以下内容在GCC 4.8.1上编译(使用--std=c++11):

struct non_default_constructible { non_default_constructible() = delete; };
template<class T>
struct dummy {
    T new_t() { return T(); }
};
int main(int argc, char** argv) {
    dummy<non_default_constructible> d;
    return 0;
}

棘手的部分是dummy<non_default_constructible>::new_t()显然格式不正确,但这并不能阻止编译器实例化dummy<non_default_constructible>

这是标准规定的行为吗?相关章节/关键词是什么?

类模板的成员函数只有在上下文需要时才会实例化,这意味着在尝试使用new_t()之前不会看到任何错误。C++标准的相关部分是:

§14.7.1隐式实例化[temp.inst]

  1. 除非函数模板专门化已显式实例化或显式专门化,否则当在需要函数定义存在的上下文中引用该专门化时,函数模板专业化将隐式实例化。除非调用是对函数模板显式专用化或显式专用类模板的成员函数的调用,否则当在需要默认参数值的上下文中调用函数时,函数模板或类模板成员函数的默认参数将被隐式实例化。

  2. 示例:

    template<class T> struct Z {
      void f();
      void g();
    };
    void h() {
      Z<int> a;     // instantiation of class Z<int> required
      Z<char>* p;   // instantiation of class Z<char> not required
      Z<double>* q; // instantiation of class Z<double> not required
      a.f();        // instantiation of Z<int>::f() required
      p->g();       // instantiation of class Z<char> required, and
                    // instantiation of Z<char>::g() required
    }
    

    本例中没有任何内容要求class Z<double>Z<int>::g()Z<char>::f()隐式实例化。--结束示例]