成员函数实例化

gTc*_*TcV 10 c++ templates

以下汇编在GCC 4.8.1(with --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;
}
Run Code Online (Sandbox Code Playgroud)

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

这是标准规定的行为吗?什么是相关的部分/关键字?

Pio*_*cki 12

只有在上下文需要时才会实例化类模板的成员函数,这意味着在尝试使用之前不会看到任何错误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
    }
    
    Run Code Online (Sandbox Code Playgroud)

    此示例中的任何内容都不需要class Z<double>,Z<int>::g()Z<char>::f()隐式实例化.- 结束例子 ]