zoukankan      html  css  js  c++  java
  • Template Instantiation

    Template Instantiation
    The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation is called a specialization.

    1. Implicit Instantiation
    Unless a template specialization has been explicitly instantiated or explicitly specialized, the compiler will generate a specialization for the template only when it needs the definition. This is called implicit instantiation.

    If the compiler must instantiate a class template specialization and the template is declared, you must also define the template.

    For example, if you declare a pointer to a class, the definition of that class is not needed and the class will not be implicitly instantiated. The following example demonstrates when the compiler instantiates a template class:

    template<class T> class X {
      public:
        X* p;
        void f();
        void g();
    };
     
    X<int>* q;
    X<int> r;
    X<float>* s;
    r.f();
    s->g();
     

    The compiler requires the instantiation of the following classes and functions:

        * X<int> when the object r is declared
        * X<int>::f() at the member function call r.f()
        * X<float> and X<float>::g() at the class member access function call s->g()

    Therefore, the functions X<T>::f() and X<T>::g() must be defined in order for the above example to compile. (The compiler will use the default constructor of class X when it creates object r.) The compiler does not require the instantiation of the following definitions:

        * class X when the pointer p is declared
        * X<int> when the pointer q is declared
        * X<float> when the pointer s is declared

        
    2. Explicit Instantiation
    You can explicitly tell the compiler when it should generate a definition from a template. This is called explicit instantiation.

    Syntax - Explicit Instantiation Declaration
     
    >>-template--template_declaration------------------------------><
     
     

    The following are examples of explicit instantiations:

    template<class T> class Array { void mf(); };
    template class Array<char>;      // explicit instantiation
    template void Array<int>::mf();  // explicit instantiation
     
    template<class T> void sort(Array<T>& v) { }
    template void sort(Array<char>&); // explicit instantiation
  • 相关阅读:
    asp.net(c#)网页跳转七种方法小结
    asp.net用Zxing库实现条形码输出的具体实现
    SQL中 patindex函数的用法
    escape()、encodeURI()、encodeURIComponent()区别详解
    sql语句分页代码
    memcache安装
    LVS和Haproxy机器必须注意的几个参数
    Redis 三主三从集群搭建
    mogodb安装步骤及注意事项
    系统故障等级和故障报告规定
  • 原文地址:https://www.cnblogs.com/taoxu0903/p/1365643.html
Copyright © 2011-2022 走看看