Home > database >  Explicit template instantiation example
Explicit template instantiation example

Time:10-07

I am currently reading a book and it has the following example:

//ch4_4_class_template_explicit.cpp
#include <iostream>

using namespace std;
template < typename T > //line A
  struct A {
    A(T init): val(init) {}
    virtual T foo();
    T val;
  }; //line B
//line C
template < class T > //T in this line is template parameter
  T A < T > ::foo() { //the 1st T refers to function return type,
    //the T in <> specifies that this function's template
    //parameter is also the class template parameter
    return val;
  } //line D
extern template struct A < int > ; //line E
#if 0 //line F
int A < int > ::foo() {
  return val   1;
}
#endif //line G
int main(void) {
  A < double > x(5);
  A < int > y(5);
  cout << "fD=" << x.foo() << ",fI=" << y.foo() << endl;
  return 0; //output: fD=5,fI=6
}

Can someone explain to me what the line

extern template struct A < int > ;

does and why the second definition for foo()? I understand what explicit template instantiation is and why it is sometimes useful, but the use of extern is not really clear to me.

The book has the following explanation for this line:

Using the extern keyword prevents implicit instantiations of that function template (see the next section for more details).

So extern prevents us from doing the following?:

auto obj = A<int>;

The second definition then negates the extern? I really can't understand this example.

Edit 1: added commented code.

Edit 2: I am almost sure that my understanding is correct. But thanks for answering.

Explanation from the book:
In the preceding code block, we defined a class template between lines A and B, and then we implemented its member function, foo(), from lines C to line D. Next, we explicitly instantiated it for the int type at line E. Since the code block between lines F and line G is commented out (which means that there is no corresponding definition of foo() for this explicit int type instantiation), we have a linkage error. To fix this, we need to replace #if 0 with #if 1 at line F.

CodePudding user response:

Maybe this help you to unsderstand.

From the C 20 (13.9.2 Explicit instantiation)

2 The syntax for explicit instantiation is:

explicit-instantiation:
    externopt template declaration

There are two forms of explicit instantiation: an explicit instantiation definition and an explicit instantiation declaration. An explicit instantiation declaration begins with the extern keyword.

So this line

extern template struct A < int > ;

is an explicit instantiation declaration of the class specialization struct A<int>.

  • Related